-
Notifications
You must be signed in to change notification settings - Fork 0
/
Buy and Sell a Share at most twice(TLE).cpp
55 lines (43 loc) · 1.19 KB
/
Buy and Sell a Share at most twice(TLE).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
//{ Driver Code Starts
//Initial Template for C++
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
int solve(vector<int>&prices,int curr,int canBuy,int left){
if( curr==prices.size()) return 0;
if(left==0) return 0;
int profit=0;
if(canBuy){
int choice1=-prices[curr]+solve(prices,curr+1,0,left);
int choice2=solve(prices,curr+1,1,left);
profit=max(choice1,choice2);
}else{
int choice1=prices[curr]+solve(prices,curr+1,1,left-1);
int choice2=solve(prices,curr+1,0,left);
profit=max(choice1,choice2);
}
return profit;
}
public:
//User function Template for C++
int maxProfit(vector<int>&prices){
//Write your code here..
return solve(prices,0,1,2);
}
};
//{ Driver Code Starts.
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<int> price(n);
for(int i=0;i<n;i++) cin>>price[i];
Solution obj;
cout<<obj.maxProfit(price)<<endl;
}
}
// } Driver Code Ends