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++
#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;
}
|
Time complexity: O(n^2) where n is size of given stock array
Auxiliary Space: O(1) as it is using constant space for variables
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 the 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 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.
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
<< " 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;
}
|
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)
Auxiliary Space: O(1)
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.
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;
}
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Please refer complete article on Stock Buy Sell to Maximize Profit for more details!
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!