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

如果能随便交易呢?不限次数的交易。那就是很简单的道理,只要是低买高卖就可以.O(n)的复杂度。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
     if (!prices.size()){
         return 0;
     }
     int max_profit = 0, pre_max = 0;
     int start = prices[0];
     int i = 1;
     for (;i < prices.size(); i++){
        if (prices[i] > prices[i -1]){
            continue;
        }
        max_profit += prices[i -1] - start;
        start = prices[i];
     }
     if (prices[i -1] > start){
       max_profit += prices[i -1] - start;
     }
     return max_profit;
    }
};

 

posted @ 2013-02-28 21:25  一只会思考的猪  阅读(117)  评论(0编辑  收藏  举报