LeetCode—122. Best Time to Buy and Sell Stock II

LeetCode—122. Best Time to Buy and Sell Stock II

题目

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
这道题是121. Best Time to Buy and Sell Stock的进阶。121要求只能买卖一次,这道题则不限制买卖次数。
在这里插入图片描述

思路及解法

方法和121是一样的。相邻位置的元素做差,然后求和。只要后面的数比前面的数大,就可以求和。没毛病,直接看代码。

代码

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

猜你喜欢

转载自blog.csdn.net/pnnngchg/article/details/82869184