-
Notifications
You must be signed in to change notification settings - Fork 481
/
0188.cpp
31 lines (29 loc) · 815 Bytes
/
0188.cpp
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
#include <vector>
#include <algorithm>
using namespace std;
static int x = []() {std::ios::sync_with_stdio(false); cin.tie(0); return 0; }();
class Solution
{
public:
int maxProfit(int k, vector<int>& prices)
{
if (k >= prices.size() / 2) return greedy(prices);
vector<int> buys(k+1, -prices[0]), sells(k+1, 0);
for (int i = 0; i < prices.size(); ++i)
{
for (int j = 1; j <= k; ++j)
{
buys[j] = max(buys[j], sells[j - 1] - prices[i]);
sells[j] = max(sells[j], buys[j] + prices[i]);
}
}
return sells.back();
}
private:
int greedy(vector<int>& p)
{
int res = 0;
for (int i = 1; i < p.size(); ++i) res += max(0, p[i] - p[i - 1]);
return res;
}
};