首页 > 其他 > 详细

122. Best Time to Buy and Sell Stock II (Array)

时间:2015-10-14 19:55:00      阅读:150      评论:0      收藏:0      [点我收藏+]

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(vector<int> &prices) {
        if(prices.empty()) return 0;
        if(prices.size() == 1) return 0;
        int maxProfit = 0;
        int buyPrice = 0;
        int prePrice;
        bool asc = false; //if in ascending sequence
        
        vector<int>::iterator it= prices.begin(); 
        prePrice = *it;
        it++;
        for(; it < prices.end(); it++)
        {
            if ((*it)>prePrice)
            {
                if(!asc) //find the first element in the ascending sequence
                {
                    buyPrice = prePrice;
                    asc = true;
                }
            }
            else  if ((*it)< prePrice)
            {
                if(asc) //find the last element in the ascending sequence
                {
                    maxProfit = prePrice - buyPrice + maxProfit;
                    asc = false;
                }
            }
            prePrice = *it;
        }
        if(asc)
        {
            maxProfit = prePrice - buyPrice + maxProfit;
        }
        return maxProfit;
    }
};

 

122. Best Time to Buy and Sell Stock II (Array)

原文:http://www.cnblogs.com/qionglouyuyu/p/4878340.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!