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

82 阅读1分钟

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

class Solution {
    public int maxProfit(int[] prices) {
        int res = 0;
        if(prices==null || prices.length==0){
            return 0;
        }
        int len =prices.length;

        int high = prices[0];
        int low = prices[0];
        int i=0;
        while(i<len-1){
           //计算买入
            while(i<len-1 && prices[i]>=prices[i+1]){
                i++;
            }
            low =prices[i];
            //计算卖出
             while(i<len-1 && prices[i]<=prices[i+1]){
                i++;
            }
            high =prices[i];
            //计算获利
            res += high-low;
        }
        return res;
    }
}