您的位置:首页 > 其它

LeetCode Best Time to Buy and Sell Stock III

2013-01-05 22:52 519 查看
class Solution {
public:
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int profit = 0;
int len = prices.size();

if (len < 2) {
return profit;
}

vector<int> left (len);
vector<int> right (len);
int low = prices[0];
int high = prices[len - 1];

left[0] = 0;
for (int i = 1; i < len; i++) {
low = min(low, prices[i - 1]);
left[i] = max(left[i - 1], prices[i] - low);
}

right[len - 1] = 0;
for (int j = len - 2; j > -1; j--) {
high = max(high, prices[j + 1]);
right[j] = max(right[j + 1], high - prices[j]);
}

for (int k = 0; k < len; k++) {
profit = max(profit, left[k] + right[k]);
}

return profit;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: