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

链接

122. Best Time to Buy and Sell Stock II

题意

给定一个数组,第i个数代表第i天股票的价格。设计算法找出最大收益。注意买股票前必须将已有的卖掉。

思路

遍历数组,只要后一天的价格高于前一天的价格,那么就将两天之差加入利润即可。

代码

Java :

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

思考

这道题的解法相当于有“预知功能”,只要发现后一天的价格高于前一天的价格,那么就先买入,等待下一天卖出。

posted @ 2017-05-12 16:39  zyoung  阅读(105)  评论(0编辑  收藏  举报