The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days. For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by buying on day 0, selling on day 3. Again buy on day 4 and sell on day 6. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all.
Naive approach: A simple approach is to try buying the stocks and selling them on every single day when profitable and keep updating the maximum profit so far.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;// Function to return the maximum profit// that can be made after buying and// selling the given stocksint maxProfit(int price[], int start, int end){ // If the stocks can't be bought if (end <= start) return 0; // Initialise the profit int profit = 0; // The day at which the stock // must be bought for (int i = start; i < end; i++) { // The day at which the // stock must be sold for (int j = i + 1; j <= end; j++) { // If byuing the stock at ith day and // selling it at jth day is profitable if (price[j] > price[i]) { // Update the current profit int curr_profit = price[j] - price[i] + maxProfit(price, start, i - 1) + maxProfit(price, j + 1, end); // Update the maximum profit so far profit = max(profit, curr_profit); } } } return profit;}// Driver codeint main(){ int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = sizeof(price) / sizeof(price[0]); cout << maxProfit(price, 0, n - 1); return 0;} |
Java
// Java implementation of the approachimport java.util.*;class GFG{// Function to return the maximum profit// that can be made after buying and// selling the given stocksstatic int maxProfit(int price[], int start, int end){ // If the stocks can't be bought if (end <= start) return 0; // Initialise the profit int profit = 0; // The day at which the stock // must be bought for (int i = start; i < end; i++) { // The day at which the // stock must be sold for (int j = i + 1; j <= end; j++) { // If byuing the stock at ith day and // selling it at jth day is profitable if (price[j] > price[i]) { // Update the current profit int curr_profit = price[j] - price[i] + maxProfit(price, start, i - 1) + maxProfit(price, j + 1, end); // Update the maximum profit so far profit = Math.max(profit, curr_profit); } } } return profit;}// Driver codepublic static void main(String[] args){ int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = price.length; System.out.print(maxProfit(price, 0, n - 1));}}// This code is contributed by PrinciRaj1992 |
Python3
# Python3 implementation of the approach# Function to return the maximum profit# that can be made after buying and# selling the given stocksdef maxProfit(price, start, end): # If the stocks can't be bought if (end <= start): return 0; # Initialise the profit profit = 0; # The day at which the stock # must be bought for i in range(start, end, 1): # The day at which the # stock must be sold for j in range(i+1, end+1): # If byuing the stock at ith day and # selling it at jth day is profitable if (price[j] > price[i]): # Update the current profit curr_profit = price[j] - price[i] +\ maxProfit(price, start, i - 1)+ \ maxProfit(price, j + 1, end); # Update the maximum profit so far profit = max(profit, curr_profit); return profit;# Driver codeif __name__ == '__main__': price = [100, 180, 260, 310, 40, 535, 695]; n = len(price); print(maxProfit(price, 0, n - 1));# This code is contributed by Rajput-Ji |
C#
// C# implementation of the approachusing System;class GFG{// Function to return the maximum profit// that can be made after buying and// selling the given stocksstatic int maxProfit(int []price, int start, int end){ // If the stocks can't be bought if (end <= start) return 0; // Initialise the profit int profit = 0; // The day at which the stock // must be bought for (int i = start; i < end; i++) { // The day at which the // stock must be sold for (int j = i + 1; j <= end; j++) { // If byuing the stock at ith day and // selling it at jth day is profitable if (price[j] > price[i]) { // Update the current profit int curr_profit = price[j] - price[i] + maxProfit(price, start, i - 1) + maxProfit(price, j + 1, end); // Update the maximum profit so far profit = Math.Max(profit, curr_profit); } } } return profit;}// Driver codepublic static void Main(String[] args){ int []price = { 100, 180, 260, 310, 40, 535, 695 }; int n = price.Length; Console.Write(maxProfit(price, 0, n - 1));}}// This code is contributed by PrinciRaj1992 |
Output:
865
Efficient approach: If we are allowed to buy and sell only once, then we can use following algorithm. Maximum difference between two elements. Here we are allowed to buy and sell multiple times.
Following is algorithm for this problem.
- Find the local minima and store it as starting index. If not exists, return.
- Find the local maxima. and store it as ending index. If we reach the end, set the end as ending index.
- Update the solution (Increment count of buy sell pairs)
- Repeat the above steps if end is not reached.
C++
// C++ Program to find best buying and selling days#include <bits/stdc++.h>using namespace std;// This function finds the buy sell// schedule for maximum profitvoid stockBuySell(int price[], int n){ // Prices must be given for at least two days if (n == 1) return; // Traverse through given price array int i = 0; while (i < n - 1) { // Find Local Minima // Note that the limit is (n-2) as we are // comparing present element to the next element while ((i < n - 1) && (price[i + 1] <= price[i])) i++; // If we reached the end, break // as no further solution possible if (i == n - 1) break; // Store the index of minima int buy = i++; // Find Local Maxima // Note that the limit is (n-1) as we are // comparing to previous element while ((i < n) && (price[i] >= price[i - 1])) i++; // Store the index of maxima int sell = i - 1; cout << "Buy on day: " << buy << "\t Sell on day: " << sell << endl; }}// Driver codeint main(){ // Stock prices on consecutive days int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = sizeof(price) / sizeof(price[0]); // Fucntion call stockBuySell(price, n); return 0;}// This is code is contributed by rathbhupendra |
C
// Program to find best buying and selling days#include <stdio.h>// solution structurestruct Interval { int buy; int sell;};// This function finds the buy sell schedule for maximum profitvoid stockBuySell(int price[], int n){ // Prices must be given for at least two days if (n == 1) return; int count = 0; // count of solution pairs // solution vector Interval sol[n / 2 + 1]; // Traverse through given price array int i = 0; while (i < n - 1) { // Find Local Minima. Note that the limit is (n-2) as we are // comparing present element to the next element. while ((i < n - 1) && (price[i + 1] <= price[i])) i++; // If we reached the end, break as no further solution possible if (i == n - 1) break; // Store the index of minima sol[count].buy = i++; // Find Local Maxima. Note that the limit is (n-1) as we are // comparing to previous element while ((i < n) && (price[i] >= price[i - 1])) i++; // Store the index of maxima sol[count].sell = i - 1; // Increment count of buy/sell pairs count++; } // print solution if (count == 0) printf("There is no day when buying the stock will make profitn"); else { for (int i = 0; i < count; i++) printf("Buy on day: %dt Sell on day: %dn", sol[i].buy, sol[i].sell); } return;}// Driver program to test above functionsint main(){ // stock prices on consecutive days int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = sizeof(price) / sizeof(price[0]); // fucntion call stockBuySell(price, n); return 0;} |
Java
// Program to find best buying and selling daysimport java.util.ArrayList;// Solution structureclass Interval { int buy, sell;}class StockBuySell { // This function finds the buy sell schedule for maximum profit void stockBuySell(int price[], int n) { // Prices must be given for at least two days if (n == 1) return; int count = 0; // solution array ArrayList<Interval> sol = new ArrayList<Interval>(); // Traverse through given price array int i = 0; while (i < n - 1) { // Find Local Minima. Note that the limit is (n-2) as we are // comparing present element to the next element. while ((i < n - 1) && (price[i + 1] <= price[i])) i++; // If we reached the end, break as no further solution possible if (i == n - 1) break; Interval e = new Interval(); e.buy = i++; // Store the index of minima // Find Local Maxima. Note that the limit is (n-1) as we are // comparing to previous element while ((i < n) && (price[i] >= price[i - 1])) i++; // Store the index of maxima e.sell = i - 1; sol.add(e); // Increment number of buy/sell count++; } // print solution if (count == 0) System.out.println("There is no day when buying the stock " + "will make profit"); else for (int j = 0; j < count; j++) System.out.println("Buy on day: " + sol.get(j).buy + " " + "Sell on day : " + sol.get(j).sell); return; } public static void main(String args[]) { StockBuySell stock = new StockBuySell(); // stock prices on consecutive days int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = price.length; // fucntion call stock.stockBuySell(price, n); }}// This code has been contributed by Mayank Jaiswal |
Python
# Python3 Program to find # best buying and selling days# This function finds the buy sell# schedule for maximum profitdef stockBuySell(price, n): # Prices must be given for at least two days if (n == 1): return # Traverse through given price array i = 0 while (i < (n - 1)): # Find Local Minima # Note that the limit is (n-2) as we are # comparing present element to the next element while ((i < (n - 1)) and (price[i + 1] <= price[i])): i += 1 # If we reached the end, break # as no further solution possible if (i == n - 1): break # Store the index of minima buy = i i += 1 # Find Local Maxima # Note that the limit is (n-1) as we are # comparing to previous element while ((i < n) and (price[i] >= price[i - 1])): i += 1 # Store the index of maxima sell = i - 1 print("Buy on day: ",buy,"\t", "Sell on day: ",sell) # Driver code# Stock prices on consecutive daysprice = [100, 180, 260, 310, 40, 535, 695]n = len(price)# Fucntion callstockBuySell(price, n)# This is code contributed by SHUBHAMSINGH10 |
C#
// C# program to find best buying and selling daysusing System;using System.Collections.Generic;// Solution structureclass Interval { public int buy, sell;}public class StockBuySell { // This function finds the buy sell // schedule for maximum profit void stockBuySell(int []price, int n) { // Prices must be given for at least two days if (n == 1) return; int count = 0; // solution array List<Interval> sol = new List<Interval>(); // Traverse through given price array int i = 0; while (i < n - 1) { // Find Local Minima. Note that // the limit is (n-2) as we are // comparing present element // to the next element. while ((i < n - 1) && (price[i + 1] <= price[i])) i++; // If we reached the end, break // as no further solution possible if (i == n - 1) break; Interval e = new Interval(); e.buy = i++; // Store the index of minima // Find Local Maxima. Note that // the limit is (n-1) as we are // comparing to previous element while ((i < n) && (price[i] >= price[i - 1])) i++; // Store the index of maxima e.sell = i - 1; sol.Add(e); // Increment number of buy/sell count++; } // print solution if (count == 0) Console.WriteLine("There is no day when buying the stock " + "will make profit"); else for (int j = 0; j < count; j++) Console.WriteLine("Buy on day: " + sol[j].buy + " " + "Sell on day : " + sol[j].sell); return; } // Driver code public static void Main(String []args) { StockBuySell stock = new StockBuySell(); // stock prices on consecutive days int []price = { 100, 180, 260, 310, 40, 535, 695 }; int n = price.Length; // fucntion call stock.stockBuySell(price, n); }}// This code is contributed by PrinciRaj1992 |
Output:
Buy on day : 0 Sell on day: 3 Buy on day : 4 Sell on day: 6
Time Complexity: The outer loop runs till I become n-1. The inner two loops increment value of I in every iteration. So overall time complexity is O(n)
Another Approach:
The idea is to find the minimum element in the array and subtract with all elements in the array and find the maximum value.
First, we store the first element of the array in a variable.
Now compare the first element with all the
the element of the array and find the minimum element.
Then store the minimum element of the array in that variable.
Then subtract the minimum element with the entire array and find the maximum value and then at last return the max value.
Java
import java.io.*;import java.util.*;class BuyStock { public static int maxProfit(int[] prices) { int n = prices.length; int cost = 0; int maxCost = 0; if (n == 0) { return 0; } // store the first element of array in a variable int min_price = prices[0]; for (int i = 0; i < n; i++) { // now compare first element with all the // element of array and find the minimum element min_price = Math.min(min_price, prices[i]); // since min_price is smallest element of the // array so subtract with every element of the // array and return the maxCost cost = prices[i] - min_price; maxCost = Math.max(maxCost, cost); } return maxCost; } // Driver Code public static void main(String[] args) { // stock prices on consecutive days int prices[] = { 7, 1, 5, 3, 6, 4 }; System.out.print(maxProfit(prices)); }} |
5
Time Complexity: O(n)
Space complexity: O(1)
This article is compiled by Ashish Anand and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Maximum profit by buying and selling a stock at most twice | Set 2
- Maximize the total profit of all the persons
- Maximize the profit by selling at-most M products
- Maximize the profit after selling the tickets
- Maximize profit in buying and selling stocks with Rest condition
- Maximize Profit by trading stocks based on given rate per day
- Find minimum cost to buy all books
- The Stock Span Problem
- Maximum profit by buying and selling a share at most k times
- Maximum profit after buying and selling the stocks
- Maximum profit by selling N items at two markets
- Maximum profit by buying and selling a share at most K times | Greedy Approach
- Maximize arr[j] - arr[i] + arr[l] - arr[k], such that i < j < k < l
- Maximize value of (arr[i] - i) - (arr[j] - j) in an array
- Maximize number of 0s by flipping a subarray
- Maximize array sum after K negations | Set 2
- Maximize sum of consecutive differences in a circular array
- Remove array end element to maximize the sum of product
- Maximize the sum of arr[i]*i
- Maximize value of (a[i]+i)*(a[j]+j) in an array

