[LeetCode-122] Best Time to Buy and Sell Stock II

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

 

不要想太多,就是整个波动中所有上升曲线的和。

 

 1 class Solution {
 2     public:
 3         /* 大数据集妥妥的超时的暴力方法,啊!太傻了!捉急啊!!!
 4         int result;
 5  
 6         void getMaxProfit(int buy_price, int day_start, int profit_before, const vector<int>& prices) {
 7             if (day_start == prices().size()) {
 8                 if (profit_before > result) {
 9                     result = profit_before;
10                     return;
11                 }
12             }
13             for (int i = day_start; i < prices.size(); ++i) {
14                 if (prices[i] < buy_price) {
15                     getMaxProfit(prices[i], i + 1, profit_before, prices); // 买
16                     getMaxProfit(buy_price, i + 1, profit_before, prices); // 不买
17                 } else {
18                     getMaxProfit(INT_MAX, i + 1, profit_before + prices[i] - buy_price, prices); // 卖
19                     getMaxProfit(buy_price, i + 1, profit_before, prices); // 不卖
20                 }
21             }
22         }
23        
24         int maxProfit(vector<int> &prices) {
25             // Start typing your C/C++ solution below
26             // DO NOT write int main() function
27             result = 0;
28             getMaxProfit(INT_MAX, 0, 0, prices);
29             return result;
30         }
31         */
32  
33         int maxProfit(vector<int> &prices) {
34             // Start typing your C/C++ solution below
35             // DO NOT write int main() function
36             // 所有上升线段长度和......
37             if (0 == prices.size()) {
38                 return 0;
39             }
40             int max_profit = 0, last_min = prices.at(0);
41             for (int i = 1; i < prices.size(); ++i) {
42                 if (prices.at(i) < prices.at(i - 1)) {
43                     max_profit += (prices.at(i - 1) - last_min);
44                     last_min = prices.at(i);
45                 }
46             }
47             max_profit += (prices.at(prices.size() - 1) - last_min);
48             return max_profit;
49         }
50 };
View Code

 

posted on 2013-08-29 08:42  似溦若岚  阅读(130)  评论(0编辑  收藏  举报

导航