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

【Best Time to Buy and Sell Stock II】cpp

时间:2015-05-30 10:34:15      阅读:98      评论: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.size()==0 ) return 0;
            int sum_profits = 0, pre_price = prices[0];
            for ( size_t i = 1; i < prices.size(); ++i )
            {
                sum_profits += (prices[i]>pre_price) ? prices[i]-pre_price : 0;
                pre_price = prices[i];
            }
            return sum_profits;
    }
};

tips:

Greedy算法。

核心算法:如果当天的价格比前一天高,sum_profits就累加上当天的利润与前一天利润的差值(即昨天买,今天买);如果当天的价格比昨天低,则不更新sum_profits(即今天买,今天卖)。

【Best Time to Buy and Sell Stock II】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4539824.html

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