[InterviewBit] Best Time to Buy and Sell Stock atmost B times

Best Time to Buy and Sell Stock atmost B times

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int Solution::solve(vector<int> &A, int B) {
int n = A.size(), res = 0;
vector<int> dp(n + 1);
for(int i = 0; i < min(n,B); i++) {
vector<int> dpp(n + 1);
int ma = 0;
for(int j = n - 1; j >= 0; j--) {
dpp[j] = max({dp[j], ma - A[j], dpp[j+1]});
ma = max(ma, dp[j + 1] + A[j]);
res = max(res, dpp[j]);
}
swap(dp,dpp);
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/26/PS/interviewbit/best-time-to-buy-and-sell-stock-atmost-b-times/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.