Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- int maxProfit(vector<int>& prices) {
- if(prices.empty()) return 0;
- int minSoFar = prices[0];
- vector<int> arr1(prices.size());
- arr1[0] = 0;
- for(int i=1; i<prices.size(); i++){
- arr1[i] = max(arr1[i-1], prices[i] - minSoFar); //arr1[i] = max profit we can have by ending our transaction on day i-1, or by selling the stock on day i.. we take max of it...
- minSoFar = min(minSoFar, prices[i]);
- }
- int answer = 0;
- int maxSoFar = prices[prices.size()-1];
- for(int j=prices.size()-2; j>=0; j--){
- if(j==0){
- answer = max(maxSoFar-prices[j], answer);
- break;
- }
- answer = max(maxSoFar-prices[j] + arr1[j-1], answer);
- maxSoFar = max(maxSoFar, prices[j]);
- }
- return answer;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement