Maximize Profit by trading stocks based on given rate per day | C ++ program for the above approach ; Function to find the maximum profit ; Start from the last day ; Traverse and keep adding the profit until a day with price of stock higher than currentDay is obtained ; Set this day as currentDay with maximum cost of stock currently ; Return the profit ; Driver Code ; Given array of prices ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxProfit ( int * prices , int n ) { int profit = 0 , currentDay = n - 1 ; while ( currentDay > 0 ) { int day = currentDay - 1 ; while ( day >= 0 && ( prices [ currentDay ] > prices [ day ] ) ) { profit += ( prices [ currentDay ] - prices [ day ] ) ; day -- ; } currentDay = day ; } return profit ; } int main ( ) { int prices [ ] = { 2 , 3 , 5 } ; int N = sizeof ( prices ) / sizeof ( prices [ 0 ] ) ; cout << maxProfit ( prices , N ) ; return 0 ; }