码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode Best Time to Buy and Sell Stock II

时间:2014-12-02 22:30:53      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   io   ar   color   sp   for   

和上一题类似Best Time to Buy and Sell Stock,这里还是用一个数组存每天股票价格,你有很多次买入卖出的机会,但是每次买入要在前一次卖出前。

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).

思路就和上一题不一样了,应该用贪心策略,每次买入都要有收益才买入,例如,当前的价格比第二题的高的话就不买入,如果比第二天的低那果断买入,起码我第二题卖掉就有赚了。然后什么时候卖出是个要注意的,例如,1,2,3,2,5,6,那么第一次在1买入,因为2比1大,然后我们看3,比2大,所以可以到3再卖出因为和你1买入2卖出再买入2再卖出3的收益是一样的。所以2被跳过,但是现在到3之后的2了,3到2会损失,那是我们不能允许的。所以3就要卖出。然后当前就从3之后的2开始考虑,继续如上考虑,最后就可以获得做大收益。

class Solution {
public:
    int maxProfit(vector<int> &prices) 
    {
        int len = prices.size();
        int profit = 0, i = 0, maxInd = 0, curp = 0;
        while(i < len - 1)
        {
            if (prices[i] >= prices[i+1])
            {
                i++;
                continue;
            }
            maxInd = i + 1;
            curp = prices[i];
            while(i + 1 < len && prices[i] <= prices[i+1])
            {
                maxInd = i+1;
                i++;
            }
            profit += prices[maxInd] - curp;
            i = maxInd + 1;
        }
        return profit;
    }
};

 

leetcode Best Time to Buy and Sell Stock II

标签:des   style   blog   http   io   ar   color   sp   for   

原文地址:http://www.cnblogs.com/higerzhang/p/4138597.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!