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

http://www.lintcode.com/en/problem/best-time-to-buy-and-sell-stock-ii/

Discussion

可以买卖多次,就是求累计利润最大值,差价大于0就累计上。

Solution


class Solution {
public:
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    int maxProfit(vector<int> &prices) {
        // write your code here
        int result = 0;
        if(prices.size() == 0) return 0;
        for(int i=1; i<prices.size(); i++) {
            int diff = prices[i] - prices[i-1];
            if(diff >0) result += diff;
        }
        return result;
    }
};

results matching ""

    No results matching ""