【力扣 买股票的最佳时机II Java/Python】
题目
思路:
可以进行多次交易,多次买入卖出,必须在卖出后才可以买入,目标的实现利润的最大化,可以用贪心的思想。
i-1 :买入的那一天
i :卖出的那一天
temp = prices[i] - prices[i-1] :代表如果昨天买,今天卖的 临时收益。
- 如果 temp > 0,说明今天比昨天贵,卖出能赚钱 → 把这段收益加上。
- 如果 temp <= 0,说明卖了不赚钱甚至亏,就忽略。
图解:
代码:
Java版本:
class Solution {public int maxProfit(int[] prices) {int maxProfit = 0;for (int i = 1; i < prices.length; i ++) {int temp = prices[i] - prices[i - 1];if(temp > 0) {maxProfit += temp;}}return maxProfit;}
}
Python版本
class Solution(object):def maxProfit(self, prices):""":type prices: List[int]:rtype: int"""maxProfit = 0for i in range(1,len(prices)): # 注意这块要从1开始temp = prices[i] - prices[i - 1]if temp > 0:maxProfit += tempreturn maxProfit