LeetCode OJ:Best Time to Buy and Sell Stock II(股票买入卖出最佳实际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     int maxProfit(vector<int>& prices) {
 4         int sz = prices.size();
 5         if(!sz) return 0;
 6         int profit = 0;
 7         int start = 0;
 8         for(int i = 1; i < sz; ++i){
 9             if(prices[i] >= prices[i - 1])
10                 continue;
11             profit += prices[i - 1] - prices[start];
12             start = i;
13         }
14         profit += prices[sz - 1] - prices[start];
15         return profit;
16     }
17 };

 

posted @ 2015-10-29 22:23  eversliver  阅读(243)  评论(0编辑  收藏  举报