-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path188_Best_Time_to_Buy_and_Sell_Stock_IV.cpp
67 lines (56 loc) · 1.58 KB
/
188_Best_Time_to_Buy_and_Sell_Stock_IV.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Naive and Optimized DP
// Leet Code Problem.
#include <iostream>
#include <bits/stdc++.h>
#include <cmath>
using namespace std;
// Naive Solution
class Solution
{
public:
int maxProfit(int k, vector<int> &prices)
{
if (k == 0)
return 0;
if (prices.size() == 0 || prices.size() == 1)
return 0;
vector<vector<int>> dp(k + 1, vector<int>(prices.size()));
for (int i = 0; i < dp.size(); i++)
{
for (int j = 0; j < dp[i].size(); j++)
{
if (i == 0)
dp[i][j] = 0;
else if (j == 0)
dp[i][j] = 0;
else
{
int x;
int mx = INT_MIN;
for (int k = 0; k < j; k++)
{
x = prices[j] - prices[k] + dp[i - 1][k];
mx = max(x, mx);
}
dp[i][j] = max(dp[i][j - 1], mx);
}
}
}
return dp[dp.size() - 1][prices.size() - 1];
}
};
// Optimized Solution
class Solution {
public:
int maxProfit(int k, vector<int>& price) {
vector<int> dp(2*k+1, INT_MIN);
dp[0] = 0;
for(int j = 0; j < price.size(); j++) {
for(int i = 0; i+2 <= 2*k; i += 2){
dp[i+1] = max(dp[i+1], dp[i]-price[j]);
dp[i+2] = max(dp[i+2], dp[i+1]+price[j]);
}
}
return *max_element(dp.begin(), dp.end());
}
};