LeetCode 买卖股票的最佳时机III

大兔子大兔子 提交于 2020-03-08 02:52:32

LeetCode 买卖股票的最佳时机III

题目

在这里插入图片描述

示例

在这里插入图片描述
在这里插入图片描述

思路

本题试了很多次思路都没能解决这个问题,然后学习了LeetCode的一些解法,最后学习了老马的解题思路,得以完成这个题。

代码来源: https://mp.weixin.qq.com/s/0QZM_HXpPEkymeZlopwoSw

代码

int maxProfit(int* prices, int pricesSize)
{    
    if (pricesSize == 0)    
    {        
       return 0;    
    }    
    int[] leftMaxProfit = new int[prices.Length];      
    int minPrice = prices[0];                         
    for (int i = 1 ; i < pricesSize ; i++)    
    {        
        if (minPrice > prices[i])        
        {            
           minPrice = prices[i];        
        }        
        leftMaxProfit[i] = Max(prices[i] - minPrice, leftMaxProfit[i - 1]);    
    }    
    int[] rightMaxProfit = new int[pricesSize];     
    int maxPrice = prices[pricesSize - 1];   
    for (int i = pricesSize - 2; i >= 0; i--)    
    {        
        if (maxPrice < prices[i])        
        {            
           maxPrice = prices[i];        
        }        
        rightMaxProfit[i] = Max(maxPrice - prices[i], rightMaxProfit[i + 1]);    
    }    
    int maxProfit = 0;    
    for (int i = 0; i < pricesSize; i++)    
    {        
        maxProfit = Max(maxProfit, leftMaxProfit[i] + rightMaxProfit[i]);    
    }   
    return maxProfit;   
}

在这里插入图片描述

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!