Maximize Profit by trading stocks based on given rate per day | 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 ; Given array of prices ; Function call
function maxProfit ( prices , n ) { let profit = 0 , currentDay = n - 1 ; while ( currentDay > 0 ) { let day = currentDay - 1 ; while ( day >= 0 && ( prices [ currentDay ] > prices [ day ] ) ) { profit += ( prices [ currentDay ] - prices [ day ] ) ; day -- ; } currentDay = day ; } return profit ; } let prices = [ 2 , 3 , 5 ] ; let N = prices . length ; document . write ( maxProfit ( prices , N ) ) ;