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
def maxProfit ( prices , n ) : NEW_LINE INDENT profit = 0 NEW_LINE currentDay = n - 1 NEW_LINE while ( currentDay > 0 ) : NEW_LINE INDENT day = currentDay - 1 NEW_LINE while ( day >= 0 and ( prices [ currentDay ] > prices [ day ] ) ) : NEW_LINE INDENT profit += ( prices [ currentDay ] - prices [ day ] ) NEW_LINE day -= 1 NEW_LINE DEDENT currentDay = day ; NEW_LINE DEDENT return profit ; NEW_LINE DEDENT prices = [ 2 , 3 , 5 ] NEW_LINE N = len ( prices ) NEW_LINE print ( maxProfit ( prices , N ) ) NEW_LINE