[LeetCode] Best Time to Buy and Sell Stock II

http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

哈哈, 状态不错, 虽然很水, 但是很快就ac了, 感觉还是很高兴~

思路就是, 找到所有递增序列, 然后最低买, 最高卖.

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int> &prices) {
 4         int cur = 1;
 5         int low = 0, high = 0;
 6         int profit = 0;
 7         while (cur < prices.size()) {
 8             if (prices[cur] > prices[high]) {
 9                 high = cur;
10             } 
11             if (prices[cur] <= prices[high] || cur == prices.size() - 1) {
12                 profit += prices[high] - prices[low];
13                 low = high = cur;
14             }
15             cur++;
16         }
17         return profit;
18     }
19 };

 

posted @ 2013-11-10 20:00  NextLife  阅读(157)  评论(0)    收藏  举报