leetcode - Best Time to Buy and Sell Stock III

来源:互联网 发布:caffe box 编辑:程序博客网 时间:2024/05/16 12:05

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 at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

class Solution {public:    int maxProfit(std::vector<int> &prices) {if(prices.size() < 1) return 0;int max = INT_MIN,min = INT_MAX,cur = 0,s = 0;std::vector<int> before(prices.size());std::vector<int> after(prices.size());for (int i = 0; i < prices.size(); i++){if(prices[i] < min) min = prices[i];cur = prices[i] - min;if(cur > s) s = cur;before[i] = s;}s = 0;for (int i = prices.size() - 1; i >= 0; i--){if(prices[i] > max) max = prices[i];cur = max - prices[i];if(cur > s) s= cur;after[i] = s;}for (int i = 0; i < prices.size(); i++){cur = before[i] + after[i];if(cur > s) s = cur;}return s;    }};


0 0