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

Best Time to Buy and Sell Stock II

时间:2014-08-14 23:05:56      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   for   ar   cti   

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 class Solution {
 2 public:
 3     int maxProfit( vector<int> &prices ) {
 4         if( prices.empty() ) { return 0; }
 5         int curMin = prices[0], profit = 0;
 6         int i = 0, size = prices.size();
 7         while( ++i < size ) {
 8             if( prices[i] <= prices[i-1] ) { continue; }
 9             curMin = prices[i-1];
10             while( i < size && prices[i] > prices[i-1] ) { ++i; }
11             profit += prices[i-1] - curMin;
12         }
13         return profit;
14     }
15 };

下面是网上看到的更加简洁的实现:

 1 class Solution {
 2 public:
 3     int maxProfit( vector<int> &prices ) {
 4         if( prices.empty() ) { return 0; }
 5         int profit = 0;
 6         for( size_t i = 1; i != prices.size(); ++i ) {
 7             if( prices[i] > prices[i-1] ) { profit += prices[i] - prices[i-1]; }
 8         }
 9         return profit;
10     }
11 };

 

Best Time to Buy and Sell Stock II,布布扣,bubuko.com

Best Time to Buy and Sell Stock II

标签:des   style   blog   color   io   for   ar   cti   

原文地址:http://www.cnblogs.com/moderate-fish/p/3913268.html

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