122 Best time to buy and sell stock ii

从前往后扫一遍, 相邻两个数之差大于零的话就加到结果。

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

 

posted on 2015-05-22 08:02  kikiUr  阅读(97)  评论(0编辑  收藏  举报