Best Time to Buy and Sell Stock

Description

Example

Lintcode_ladder

Method

  1. x
  2. x

Example

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

Similar problems

x

Tags

x

results matching ""

    No results matching ""