The cost of a stock on each day is given in an array. Find the maximum profit that you can make by buying and selling on those days. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all.
Examples:
Input: arr[] = {100, 180, 260, 310, 40, 535, 695}
Output: 865
Explanation: Buy the stock on day 0 and sell it on day 3 => 310 – 100 = 210
Buy the stock on day 4 and sell it on day 6 => 695 – 40 = 655
Maximum Profit = 210 + 655 = 865
Input: arr[] = {4, 2, 2, 2, 4}
Output: 2
Explanation: Buy the stock on day 1 and sell it on day 4 => 4 – 2 = 2
Maximum Profit = 2
A simple approach is to try buying the stocks and selling them every single day when profitable and keep updating the maximum profit so far.
Follow the steps below to solve the problem:
- Try to buy every stock from start to end – 1
- After that again call the maxProfit function to calculate answer
- curr_profit = price[j] – price[i] + maxProfit(start, i – 1) + maxProfit(j + 1, end)
- profit = max(profit, curr_profit)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxProfit( int price[], int start, int end)
{
if (end <= start)
return 0;
int profit = 0;
for ( int i = start; i < end; i++) {
for ( int j = i + 1; j <= end; j++) {
if (price[j] > price[i]) {
int curr_profit
= price[j] - price[i]
+ maxProfit(price, start, i - 1)
+ maxProfit(price, j + 1, end);
profit = max(profit, curr_profit);
}
}
}
return profit;
}
int 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;
}
|
C
#include <stdio.h>
#define max(x, y) (((x) > (y)) ? (x) : (y))
#define min(x, y) (((x) < (y)) ? (x) : (y))
int maxProfit( int price[], int start, int end)
{
if (end <= start)
return 0;
int profit = 0;
for ( int i = start; i < end; i++) {
for ( int j = i + 1; j <= end; j++) {
if (price[j] > price[i]) {
int curr_profit
= price[j] - price[i]
+ maxProfit(price, start, i - 1)
+ maxProfit(price, j + 1, end);
profit = max(profit, curr_profit);
}
}
}
return profit;
}
int main()
{
int price[] = { 100, 180, 260, 310, 40, 535, 695 };
int n = sizeof (price) / sizeof (price[0]);
printf ( "%d" , maxProfit(price, 0, n - 1));
return 0;
}
|
Java
import java.util.*;
class GFG {
static int maxProfit( int price[], int start, int end)
{
if (end <= start)
return 0 ;
int profit = 0 ;
for ( int i = start; i < end; i++) {
for ( int j = i + 1 ; j <= end; j++) {
if (price[j] > price[i]) {
int curr_profit
= price[j] - price[i]
+ maxProfit(price, start, i - 1 )
+ maxProfit(price, j + 1 , end);
profit = Math.max(profit, curr_profit);
}
}
}
return profit;
}
public 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 ));
}
}
|
Python3
def maxProfit(price, start, end):
if (end < = start):
return 0
profit = 0
for i in range (start, end, 1 ):
for j in range (i + 1 , end + 1 ):
if (price[j] > price[i]):
curr_profit = price[j] - price[i] + \
maxProfit(price, start, i - 1 ) + \
maxProfit(price, j + 1 , end)
profit = max (profit, curr_profit)
return profit
if __name__ = = '__main__' :
price = [ 100 , 180 , 260 , 310 , 40 , 535 , 695 ]
n = len (price)
print (maxProfit(price, 0 , n - 1 ))
|
C#
using System;
class GFG {
static int maxProfit( int [] price, int start, int end)
{
if (end <= start)
return 0;
int profit = 0;
for ( int i = start; i < end; i++) {
for ( int j = i + 1; j <= end; j++) {
if (price[j] > price[i]) {
int curr_profit
= price[j] - price[i]
+ maxProfit(price, start, i - 1)
+ maxProfit(price, j + 1, end);
profit = Math.Max(profit, curr_profit);
}
}
}
return profit;
}
public 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));
}
}
|
Javascript
<script>
function maxProfit( price, start, end)
{
if (end <= start)
return 0;
let profit = 0;
for (let i = start; i < end; i++) {
for (let j = i + 1; j <= end; j++) {
if (price[j] > price[i]) {
let curr_profit = price[j] - price[i]
+ maxProfit(price, start, i - 1)
+ maxProfit(price, j + 1, end);
profit = Math.max(profit, curr_profit);
}
}
}
return profit;
}
let price = [ 100, 180, 260, 310,
40, 535, 695 ];
let n = price.length;
document.write(maxProfit(price, 0, n - 1));
</script>
|
Time Complexity: O(N2), Trying to buy every stock and exploring all possibilities.
Auxiliary Space: O(1)
Stock Buy Sell to Maximize Profit using Local Maximum and Local Minimum:
If we are allowed to buy and sell only once, then we can use the algorithm discussed in maximum difference between two elements. Here we are allowed to buy and sell multiple times.
Follow the steps below to solve the problem:
- Find the local minima and store it as starting index. If it does not exists, return.
- Find the local maxima. And store it as an ending index. If we reach the end, set the end as the ending index.
- Update the solution (Increment count of buy-sell pairs)
- Repeat the above steps if the end is not reached.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void stockBuySell( int price[], int n)
{
if (n == 1)
return ;
int i = 0;
while (i < n - 1) {
while ((i < n - 1) && (price[i + 1] <= price[i]))
i++;
if (i == n - 1)
break ;
int buy = i++;
while ((i < n) && (price[i] >= price[i - 1]))
i++;
int sell = i - 1;
cout << "Buy on day: " << buy
<< "\t Sell on day: " << sell << endl;
}
}
int main()
{
int price[] = { 100, 180, 260, 310, 40, 535, 695 };
int n = sizeof (price) / sizeof (price[0]);
stockBuySell(price, n);
return 0;
}
|
C
#include <stdio.h>
struct Interval {
int buy;
int sell;
};
void stockBuySell( int price[], int n)
{
if (n == 1)
return ;
int count = 0;
Interval sol[n / 2 + 1];
int i = 0;
while (i < n - 1) {
while ((i < n - 1) && (price[i + 1] <= price[i]))
i++;
if (i == n - 1)
break ;
sol[count].buy = i++;
while ((i < n) && (price[i] >= price[i - 1]))
i++;
sol[count].sell = i - 1;
count++;
}
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 ;
}
int main()
{
int price[] = { 100, 180, 260, 310, 40, 535, 695 };
int n = sizeof (price) / sizeof (price[0]);
stockBuySell(price, n);
return 0;
}
|
Java
import java.util.ArrayList;
class Interval {
int buy, sell;
}
class StockBuySell {
void stockBuySell( int price[], int n)
{
if (n == 1 )
return ;
int count = 0 ;
ArrayList<Interval> sol = new ArrayList<Interval>();
int i = 0 ;
while (i < n - 1 ) {
while ((i < n - 1 )
&& (price[i + 1 ] <= price[i]))
i++;
if (i == n - 1 )
break ;
Interval e = new Interval();
e.buy = i++;
while ((i < n) && (price[i] >= price[i - 1 ]))
i++;
e.sell = i - 1 ;
sol.add(e);
count++;
}
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();
int price[] = { 100 , 180 , 260 , 310 , 40 , 535 , 695 };
int n = price.length;
stock.stockBuySell(price, n);
}
}
|
Python3
def stockBuySell(price, n):
if (n = = 1 ):
return
i = 0
while (i < (n - 1 )):
while ((i < (n - 1 )) and
(price[i + 1 ] < = price[i])):
i + = 1
if (i = = n - 1 ):
break
buy = i
i + = 1
while ((i < n) and (price[i] > = price[i - 1 ])):
i + = 1
sell = i - 1
print ( "Buy on day: " , buy, "\t" ,
"Sell on day: " , sell)
price = [ 100 , 180 , 260 , 310 , 40 , 535 , 695 ]
n = len (price)
stockBuySell(price, n)
|
C#
using System;
using System.Collections.Generic;
class Interval {
public int buy, sell;
}
public class StockBuySell {
void stockBuySell( int [] price, int n)
{
if (n == 1)
return ;
int count = 0;
List<Interval> sol = new List<Interval>();
int i = 0;
while (i < n - 1) {
while ((i < n - 1)
&& (price[i + 1] <= price[i]))
i++;
if (i == n - 1)
break ;
Interval e = new Interval();
e.buy = i++;
while ((i < n) && (price[i] >= price[i - 1]))
i++;
e.sell = i - 1;
sol.Add(e);
count++;
}
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 ;
}
public static void Main(String[] args)
{
StockBuySell stock = new StockBuySell();
int [] price = { 100, 180, 260, 310, 40, 535, 695 };
int n = price.Length;
stock.stockBuySell(price, n);
}
}
|
Javascript
<script>
function stockBuySell(price, n) {
if (n == 1)
return ;
let i = 0;
while (i < n - 1) {
while ((i < n - 1) && (price[i + 1] <= price[i]))
i++;
if (i == n - 1)
break ;
let buy = i++;
while ((i < n) && (price[i] >= price[i - 1]))
i++;
let sell = i - 1;
document.write(`Buy on day: ${buy}
Sell on day: ${sell}<br>`);
}
}
let price = [100, 180, 260, 310, 40, 535, 695];
let n = price.length;
stockBuySell(price, n);
</script>
|
OutputBuy on day: 0 Sell on day: 3
Buy on day: 4 Sell on day: 6
Time Complexity: O(N), The outer loop runs till I become n-1. The inner two loops increment the value of I in every iteration.
Auxiliary Space: O(1)
Stock Buy Sell to Maximize Profit using Valley Peak Approach:
In this approach, we just need to find the next greater element and subtract it from the current element so that the difference keeps increasing until we reach a minimum. If the sequence is a decreasing sequence, so the maximum profit possible is 0.
Follow the steps below to solve the problem:
- maxProfit = 0
- if price[i] > price[i – 1]
- maxProfit = maxProfit + price[i] – price[i – 1]
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
#define fl(i, a, b) for (int i = a; i < b; i++)
int maxProfit( int * prices, int size)
{
int maxProfit = 0;
fl(i, 1, size) if (prices[i] > prices[i - 1]) maxProfit
+= prices[i] - prices[i - 1];
return maxProfit;
}
int main()
{
int prices[] = { 100, 180, 260, 310, 40, 535, 695 };
int N = sizeof (prices) / sizeof (prices[0]);
cout << maxProfit(prices, N) << endl;
return 0;
}
|
C
#include <stdio.h>
#define max(x, y) (((x) > (y)) ? (x) : (y))
#define min(x, y) (((x) < (y)) ? (x) : (y))
int maxProfit( int prices[], int size)
{
int ans = 0;
for ( int i = 1; i < size; i++) {
if (prices[i] > prices[i - 1])
ans += prices[i] - prices[i - 1];
}
return ans;
}
int main()
{
int price[] = { 100, 180, 260, 310, 40, 535, 695 };
int n = sizeof (price) / sizeof (price[0]);
printf ( "%d" , maxProfit(price, n));
return 0;
}
|
Java
import java.io.*;
class GFG {
static int maxProfit( int prices[], int size)
{
int maxProfit = 0 ;
for ( int i = 1 ; i < size; i++)
if (prices[i] > prices[i - 1 ])
maxProfit += prices[i] - prices[i - 1 ];
return maxProfit;
}
public static void main(String[] args)
{
int price[] = { 100 , 180 , 260 , 310 , 40 , 535 , 695 };
int n = price.length;
System.out.println(maxProfit(price, n));
}
}
|
Python3
def max_profit(prices: list , days: int ) - > int :
profit = 0
for i in range ( 1 , days):
if prices[i] > prices[i - 1 ]:
profit + = prices[i] - prices[i - 1 ]
return profit
if __name__ = = '__main__' :
prices = [ 100 , 180 , 260 , 310 , 40 , 535 , 695 ]
profit = max_profit(prices, len (prices))
print (profit)
|
C#
using System;
class GFG {
static int maxProfit( int [] prices, int size)
{
int maxProfit = 0;
for ( int i = 1; i < size; i++)
if (prices[i] > prices[i - 1])
maxProfit += prices[i] - prices[i - 1];
return maxProfit;
}
public static void Main( string [] args)
{
int [] price = { 100, 180, 260, 310, 40, 535, 695 };
int n = price.Length;
Console.WriteLine(maxProfit(price, n));
}
}
|
Javascript
<script>
function maxProfit(prices , size) {
var maxProfit = 0;
for (i = 1; i < size; i++)
if (prices[i] > prices[i - 1])
maxProfit += prices[i] - prices[i - 1];
return maxProfit;
}
var price = [ 100, 180, 260, 310, 40, 535, 695 ];
var n = price.length;
document.write(maxProfit(price, n));
</script>
|
Time Complexity: O(N), Traversing over the array of size N.
Auxiliary Space: O(1)