leetcode 122. The best time to buy and sell stocks || (Java greedy)

Can buy and sell a stock, and seeking to maximize profits and need to be divided into several arrays increasing sequence according to the order, seeking maximum interpolation each incremental sequence, I began to think complicated, and with the | same ideas, thinking to pay more a ans on it, but that would be too much trouble, in fact, the code is very simple, only need to determine prices [i] and prices [i-1] of the size, if incremental, use ans their difference can add a.

 

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

 

Guess you like

Origin www.cnblogs.com/y1040511302/p/11521469.html