美文网首页
122. 买卖股票的最佳时机 II

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

作者: bangbang2 | 来源:发表于2020-08-10 09:05 被阅读0次
image.png

与买卖股票1相比,可以进行多次买卖
首先需要明白一个道理,在一个函数不断的上升,下降
利润最大的是函数的每一段上升的线段和
所以只需要比较相邻两个节点是不是上升,如果是上升就加入到利润,不是上升段,就不处理,继续去执行

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

相关文章

网友评论

      本文标题:122. 买卖股票的最佳时机 II

      本文链接:https://www.haomeiwen.com/subject/hztrdktx.html