LeetCode之旅(C/C++/Java/Python):122. 买卖股票的最佳时机 II

版权声明:欢迎转载,不必客气。 https://blog.csdn.net/CSDN_FengXingwei/article/details/89194333

PS:不明之处,请君留言,以期共同进步!

题目描述:

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

示例 1:

输入: [7,1,5,3,6,4]
输出: 7
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。

示例 2:

输入: [1,2,3,4,5]
输出: 4
解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。
因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。

示例 3:

输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。

代码实现:

思路一:峰谷法

假设给定数组:[7,1,5,3,6,4],我们将其绘制成图表:
在这里插入图片描述
分析图表可知,先求相邻的波峰和波谷之差(即peak - valley),再求这些差值之和,这样得到的结果最大。因为如上图所示,A+B>C,而且总是这样。

C语言
int maxProfit(int* prices, int pricesSize) 
{
    if(NULL == prices || 0 == pricesSize)
        return 0;
    int valley = prices[0];//这里使用到下标,因此必须进行前面的判断
    int peak = prices[0];
    int maxProfix = 0;
    int i = 0;
    while(i < pricesSize - 1)
    {
        while(i < pricesSize - 1 && prices[i] >= prices[i + 1])
            ++i;
        valley = prices[i];
        while(i < pricesSize - 1 && prices[i] <= prices[i + 1])
            ++i;
        peak = prices[i];
        maxProfix += peak - valley;
    }
    return maxProfix;
}
C++语言
class Solution {
public:
    int maxProfit(vector<int>& prices) 
    {
        if(prices.empty()) //必须做判断,否则会报错
            return 0;
        int valley = prices[0];
        int peak = prices[0];
        int maxProfix = 0;
        int i = 0;
        while(i < prices.size() - 1)
        {
            while(i < prices.size() - 1 && prices[i] >= prices[i + 1])
                ++i;
            valley = prices[i];
            while(i < prices.size() - 1 && prices[i] <= prices[i + 1])
                ++i;
            peak = prices[i];
            maxProfix += peak - valley;
        }
        return maxProfix;
    }
};

出现过的问题:

刚开始我没有在C++代码中判断prices是否为空:

if(prices.empty()) 
	return 0;

因此在提交代码时报错:

执行出错信息:
Line 933: Char 34: runtime error: reference binding to null pointer of type 'value_type' (stl_vector.h)
最后执行的输入:[]

提示信息的含义是当输入的prices为[]即空数组时报错,所以后来我添加了判断prices是否为空代码。
但是,在C语言写的代码中即使没有此类代码:

if(NULL == prices || 0 == pricesSize)
	return 0;

也不会报错,是没有像C++中的vector那样的错误检查机制嘛?

思路二:简单的一次遍历

假设给定数组:[1, 7, 2, 3, 6, 7, 6, 7],将其绘制成图表:
在这里插入图片描述
简单的考虑问题,就像爬山一样,先翻过一座山,再翻过一座山……其实只要我们把每次上山过程中上升的海拔相加,就是我们爬完所有山需要上升的总海拔,也就是我们可以获得的最大利润。设想一下,如果我们可以隔过几座山不用爬,或者直接从第一座山上移动到最后一座山上,那岂不是能省很多力气,就是说会减少很多海拔上升的过程,然而每次海拔上升的过程都代表我们正在获利,那样的话,回到这道题中,我们就少获得了很多利润。

C语言
int maxProfit(int* prices, int pricesSize) 
{
	//没有使用下标,不必做数组是否为空的判断
    int maxProfix = 0;
    for(int i = 0; i < pricesSize - 1; ++i)
        if(prices[i] < prices[i + 1])
            maxProfix += prices[i + 1] - prices[i];
    return maxProfix;
}
C++语言
class Solution {
public:
    int maxProfit(vector<int>& prices) 
    {
        if(prices.empty())//必须做判断,不然会报错
            return 0;
        int maxProfix = 0;
        for(int i = 0; i < prices.size() - 1; ++i)
            if(prices[i] < prices[i + 1])
                maxProfix += prices[i + 1] - prices[i];
        return maxProfix;
    }
};
Java语言
class Solution {
    public int maxProfit(int[] prices) {
        int max = 0;
        int size = prices.length;
        for (int i = 0; i < size - 1; ++i)
            if (prices[i] < prices[i + 1])
                max += prices[i + 1] - prices[i];
        return max;
    }
}
Python语言
class Solution(object):
    def maxProfit(self, prices):
    	"""
        :type prices: List[int]
        :rtype: int
        """
        maxProfix = 0
        if prices == None:
            return maxProfix
        for i in range(len(prices) - 1):
            if prices[i] < prices[i + 1]:
                maxProfix += prices[i + 1] - prices[i]
        return maxProfix
Python3语言
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        maxProfix = 0
        if prices == None:
            return 0
        for i in range(len(prices) - 1):
            if prices[i] < prices[i + 1]:
                maxProfix += prices[i + 1] - prices[i]
        return maxProfix

思路三:暴力法

计算所有可能的交易组合的利润,并找出它们中的最大利润。
假设给定数组:prices = [1,2,3,4,5,…]
我们可以考虑第一笔交易是第一天买入,第二天卖出,这种情况下的最大利润是:
收益1 = (prices[1] - prices[0]) + 最大利润([3,4,5,…])
我们也可以考虑第一笔交易是第一天买入,第三天卖出,这种情况下的最大利润是:
收益2 = (prices[2] - prices[0]) + 最大利益([4,5,…])
如此类推,假设第一笔交易共有N种可能,那么最大利润就是上述N种情况中的最大值。
显然这是一种标准的递归算法。

Java语言
class Solution {
    public int maxProfit(int[] prices) {
        return calculate(prices, 0);
    }

    public int calculate(int prices[], int s) {
        if (s >= prices.length)
            return 0;
        int max = 0;
        for (int start = s; start < prices.length; start++) {
            int maxprofit = 0;
            for (int end = start + 1; end < prices.length; end++) {
                if (prices[start] < prices[end]) {
                    int profit = calculate(prices, end + 1) + prices[end] - prices[start];
                    if (profit > maxprofit)
                        maxprofit = profit;
                }
            }
            if (maxprofit > max)
                max = maxprofit;
        }
        return max;
    }
}
Python语言
class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) <= 1:
            return 0
        else:
            maxProfix = 0
            for startPos in range(len(prices) - 1):
                for endPos in range(startPos + 1, len(prices), 1):
                    if prices[endPos] > prices[startPos]:  #一种可能的第一笔交易
                        profix = prices[endPos] - prices[startPos] + self.maxProfit(prices[endPos + 1:])
                        if profix > maxProfix:
                            maxProfix = profix
            return maxProfix      

猜你喜欢

转载自blog.csdn.net/CSDN_FengXingwei/article/details/89194333