122. Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

这是一道贪心题,为了方便理解,我们可以吧每个元素的对应的点值连起来画成折线图,那么问题就变成了在这一段一段的折线图中怎么取可以取得最大的利润。

显然对于每一段能赚到钱的(即上升的折线)线段,我们都是要去取得的(因为没有次数限制)于是问题就变成了判断相邻两个点的折线是上升还是下降

class Solution {
    public int maxProfit(int[] prices) {
        int max = 0 ;
        for(int i = 0 ;i<prices.length-1;i++)
        {
            if(prices[i]<prices[i+1])
            {
                max+=(prices[i+1]-prices[i]);
            }
        }
        return max;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容