The best time to buy and sell stocks leetcode 122 2

The best time to buy and sell stocks 2

Ideas:

You can use the greedy algorithm: As long as the value of the previous day after the big day, you can sell.

class Solution {
    public int maxProfit(int[] prices) {
            if (prices.length < 1){
                        return 0;
            }
            int res = 0;
            for(int i=1;i<prices.length;i++){
                 if (prices[i] - prices[i-1] > 0){
                      res += prices[i] - prices[i-1];
                 }
            }
           return res;
    }
}
Released four original articles · won praise 0 · Views 35

Guess you like

Origin blog.csdn.net/weixin_42495589/article/details/104678435