Maximize profit in buying and selling stocks with Rest condition | C ++ program for the above problem ; If there is only one day for buying and selling no profit can be made ; Array to store Maxprofit by resting on given day ; Array to store Maxprofit by buying or resting on the given day ; Array to store Maxprofit by selling on given day ; Initially there will 0 profit ; Buying on 1 st day results in negative profit ; zero profit since selling before buying isn 't possible ; max of profit on ( i - 1 ) th day by resting and profit on ( i - 1 ) th day by selling . ; max of profit by resting on ith day and buying on ith day . ; max of profit by selling on ith day ; maxprofit ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxProfit ( int prices [ ] , int n ) { if ( n <= 1 ) return 0 ; int rest [ n ] = { 0 } ; int hold [ n ] = { 0 } ; int sold [ n ] = { 0 } ; rest [ 0 ] = 0 ; hold [ 0 ] = - prices [ 0 ] ; sold [ 0 ] = 0 ; for ( int i = 1 ; i < n ; i ++ ) { rest [ i ] = max ( rest [ i - 1 ] , sold [ i - 1 ] ) ; hold [ i ] = max ( hold [ i - 1 ] , rest [ i - 1 ] - prices [ i ] ) ; sold [ i ] = hold [ i - 1 ] + prices [ i ] ; } return max ( rest [ n - 1 ] , sold [ n - 1 ] ) ; } int main ( ) { int price [ ] = { 2 , 4 , 5 , 0 , 2 } ; int n = sizeof ( price ) / sizeof ( price [ 0 ] ) ; cout << maxProfit ( price , n ) << endl ; return 0 ; }