-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path123.cpp
More file actions
38 lines (35 loc) · 1000 Bytes
/
123.cpp
File metadata and controls
38 lines (35 loc) · 1000 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//
// 123.cpp
// LeetCode
//
// Created by 张佐玮 on 15/7/21.
// Copyright (c) 2015年 JarvisZhang. All rights reserved.
//
// Title: Best Time to Buy and Sell Stock III
//
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.empty()) {
return 0;
}
int n = (int) prices.size(), current = 0;
int singleProfit[n];
singleProfit[0] = 0;
for (int i = 0; i < n - 1; i++) {
current = max(current + prices[i+1] - prices[i], 0);
singleProfit[i+1] = max(singleProfit[i], current);
}
int reverserProfit = 0, result = 0;
current = 0;
for (int i = n - 2; i >= 0; i--) {
current = max(current + prices[i+1] - prices[i], 0);
reverserProfit = max(reverserProfit, current);
result = max(result, reverserProfit + singleProfit[i]);
}
return result;
}
};