欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

[算法刷新 day32] Leetcode:122.买卖股票的最佳时机 II, 55.跳跃游戏, 45.跳跃游戏 II-Leetcode:122.买卖股票的最佳时机 II

最编程 2024-04-21 16:45:50
...

题目:122. 买卖股票的最佳时机 II
解析:代码随想录解析

解题思路

记录当前的购入金额,当上一次卖出金额收益高于这次的卖出金额时,卖出上次,这次的记为购入金额。(没用到贪心)

代码

class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        int purchase = prices[0];
        int sell = prices[0];
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] < sell) {
                profit += (sell - purchase);
                purchase = prices[i];
            }
            sell = prices[i];
        }
        if (sell > purchase)
            profit += (sell - purchase);
        return profit;
    }
}

//贪心(今天卖了赚钱就卖,卖了亏本就不卖)
class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        for (int i = 1; i < prices.length; i++) {
            profit += Math.max(prices[i] - prices[i-1], 0);
        }
        return profit;
    }
}

总结

贪心算法代码量少阿