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
using System ; class GFG { static 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 ; } public static void Main ( String [ ] args ) { int [ ] prices = { 2 , 3 , 5 } ; int N = prices . Length ; Console . Write ( maxProfit ( prices , N ) ) ; } }