# Maximize Profit by trading stocks based on given rate per day

• Difficulty Level : Medium
• Last Updated : 13 Dec, 2022

Given an array arr[] of N positive integers which denotes the cost of selling and buying a stock on each of the N days. The task is to find the maximum profit that can be earned by buying a stock on or selling all previously bought stocks on a particular day.
Examples:

Input: arr[] = {2, 3, 5}
Output:
Explanation:
Price on Day 1 = 2. Therefore buy the stocks on Day 1 at this cost. Total_Spent = 2
Price on Day 2 = 3. Therefore buy the stocks on Day 2 at this cost. Total_Spent = 2 + 3 = 5
Price on Day 3 = 5. If the stocks are sold at this price, the profit will be maximum. Therefore sell the bought stocks on Day 3 at this cost. Total_gained = 5*2 = 10
Profit = 10 – 5 = 5
Input: arr[] = {8, 5, 1}
Output:
Explanation:
After buying any stock we can’t sell on any other day because it will lead to loss. Therefore Profit is 0.

Approach: The idea is to break the given prices of stock into different subarrays such that each subarray has the maximum value at the end of the array. Then, find the profit by subtracting each stock value from the last element in each subarray. Below are the steps:

1. Traverse the array arr[] from the end and consider arr[N – 1] as the current highest price of a stock, say maxM.
2. As long as the price is highest, all the stocks purchased previously will gain profit. Therefore, move towards the left in arr[] and keep adding maxM – arr[i] to profit for all indices until any index occurs with higher cost than maxM.
3. If a higher price than maxM is encountered, then buying it causes a loss.So set the cost of stock for that particular day, i.e. arr[i], as the current value of maxM and repeat Step 2.
4. After the array is traversed, print the sum of difference obtained in step 2 for each possible price in the arr[].

Below is the implementation of the above approach:

## C++

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

## Java

 // Java program for the above approachimport java.io.*;public class GFG{ // Function to find the maximum profitstatic int maxProfit(int[] prices, int n){    int profit = 0, currentDay = n - 1;     // Start from the last day    while (currentDay > 0)    {        int day = currentDay - 1;         // Traverse and keep adding the        // profit until a day with        // price of stock higher        // than currentDay is obtained        while (day >= 0 &&            (prices[currentDay] > prices[day]))        {            profit += (prices[currentDay] -                    prices[day]);             day--;        }         // Set this day as currentDay        // with maximum cost of stock        // currently        currentDay = day;    }     // Return the profit    return profit;} // Driver Codepublic static void main(String[] args){    // Given array of prices    int prices[] = { 2, 3, 5 };     int N = prices.length;     // Function Call    System.out.print(maxProfit(prices, N));}} // This code is contributed by Princi Singh

## Python3

 # Python3 program to implement# above approach # Function to find the maximum profitdef maxProfit(prices, n):     profit = 0    currentDay = n - 1     # Start from the last day    while (currentDay > 0):        day = currentDay - 1         # Traverse and keep adding the        # profit until a day with        # price of stock higher        # than currentDay is obtained        while (day >= 0 and              (prices[currentDay] >               prices[day])):            profit += (prices[currentDay] -                       prices[day])                                    day -= 1                 # Set this day as currentDay        # with maximum cost of stock        # currently        currentDay = day;         # Return the profit    return profit; # Driver Code # Given array of pricesprices = [ 2, 3, 5 ] N = len(prices) # Function callprint(maxProfit(prices, N)) # This code is contributed by sanjoy_62

## C#

 // C# program for the above approachusing System; class GFG{ // Function to find the maximum profitstatic int maxProfit(int[] prices, int n){    int profit = 0, currentDay = n - 1;     // Start from the last day    while (currentDay > 0)    {        int day = currentDay - 1;         // Traverse and keep adding the        // profit until a day with        // price of stock higher        // than currentDay is obtained        while (day >= 0 &&              (prices[currentDay] > prices[day]))        {            profit += (prices[currentDay] -                       prices[day]);             day--;        }         // Set this day as currentDay        // with maximum cost of stock        // currently        currentDay = day;    }     // Return the profit    return profit;} // Driver Codepublic static void Main(String[] args){         // Given array of prices    int []prices = { 2, 3, 5 };     int N = prices.Length;     // Function call    Console.Write(maxProfit(prices, N));}} // This code is contributed by amal kumar choubey

## Javascript



Output:

5

Time Complexity: O(N)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up