-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path123.买卖股票的最佳时机-iii.cpp
More file actions
47 lines (44 loc) · 1.14 KB
/
123.买卖股票的最佳时机-iii.cpp
File metadata and controls
47 lines (44 loc) · 1.14 KB
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
39
40
41
42
43
44
45
46
/*
* @lc app=leetcode.cn id=123 lang=cpp
*
* [123] 买卖股票的最佳时机 III
*/
// @lc code=start
class Solution {
public:
// 有待优化。时间复杂度较高。
int maxProfit1(vector<int>& prices, int left, int right) {
int result = 0;
int max = 0; // 记录最大者。
for (int i = right - 1; i >= left; i--)
{
if (max < prices.at(i))
{
max = prices.at(i);
}
if (max - prices.at(i) > result)
{
result = max - prices.at(i);
}
}
return result;
}
int maxProfit(vector<int>& prices) {
int result = 0;
for (int i = 0; i < prices.size(); i++)
{
// 包括左边不包括右边。
int buffer = maxProfit1(prices, 0, i) + maxProfit1(prices, i, prices.size());
if (i == 0 && buffer == 0) // 特殊情况!股价只降不升。
{
return 0;
}
if (buffer > result)
{
result = buffer;
}
}
return result;
}
};
// @lc code=end