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: 5
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: 0
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:
- Traverse the array arr[] from the end and consider arr[N – 1] as the current highest price of a stock, say maxM.
- 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.
- 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.
- 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 <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; } |
Java
// Java program for the above approach import java.io.*; public 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 |
Python3
# Python3 program to implement # above approach # Function to find the maximum profit def 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 prices prices = [ 2 , 3 , 5 ] N = len (prices) # Function call print (maxProfit(prices, N)) # This code is contributed by sanjoy_62 |
C#
// 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 |
Javascript
<script> // Javascript program for the above problem. // Function to find the maximum profit function maxProfit(prices, n) { let profit = 0, currentDay = n - 1; // Start from the last day while (currentDay > 0) { let 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 // Given array of prices let prices = [2, 3, 5]; let N = prices.length; // Function call document.write(maxProfit(prices, N)); // This code is contributed by susmitakundugoaldanga. </script> |
5
Time Complexity: O(N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!