0
点赞
收藏
分享

微信扫一扫

122. 买卖股票的最佳时机 II

晚熟的猫 2022-03-13 阅读 42

给定一个数组 prices ,其中 prices[i] 表示股票第 i 天的价格。

在每一天,你可能会决定购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以购买它,然后在 同一天 出售。
返回 你能获得的 最大 利润 。

本题关键点,一只股票;

那么假如第0天买入,第3天卖出,那么利润为:prices[3] - prices[0]。

相当于(prices[3] - prices[2]) + (prices[2] - prices[1]) + (prices[1] - prices[0])。

想到利润可分解,本题就解出来了,只需选择利润为正的部分即可;

 public int maxProfit(int[] prices) {
        int[] profits=new int[prices.length-1];
        int count=0;
        for (int i = 1; i <prices.length ; i++) {
            profits[i-1]=prices[i]-prices[i-1];
            if(profits[i-1]>0){
                count+=profits[i-1];
            }
        }
        return count;
    }

构造一个利润数组,后一天的股票价格减去前一天的股票价格为此数组的元素;

举报

相关推荐

0 条评论