Maximize Profit by trading stocks based on given rate per day

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the maximum profit
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 Code
int 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
class GFG{
  
// Function to find the maximum profit
static 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 Code
public 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
  
class GFG{
  
// Function to find the maximum profit
static 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 Code
public 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

chevron_right


Output: 

5

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

competitive-programming-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.