Best Time to Buy and Sell Stock II

Q:

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

A:

从前至后,总是先找最小值再找最大值,一直到数组尾部。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int len = prices.size();
        if (len <= 1) return 0;
        int lowest_pos = 0;
        int highest_pos = -1;
        int cur_pos = 0;
        int max_profit = 0;
        while (cur_pos < len) {
            while (prices[cur_pos] <= prices[lowest_pos] &&
                   cur_pos < len) {
                lowest_pos = cur_pos++;
            }
            
            highest_pos = lowest_pos;
            while (prices[cur_pos] >= prices[highest_pos] &&
                   cur_pos < len) {
                highest_pos = cur_pos++;
            }
            if (highest_pos > lowest_pos) max_profit += prices[highest_pos] - prices[lowest_pos];
            lowest_pos = highest_pos;
        }
        return max_profit;
    }
};

 

posted @ 2013-06-23 17:39  dmthinker  阅读(67)  评论(0)    收藏  举报