C Program For Stock Buy Sell To Maximize Profit
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 <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;
}
|
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) since using constant variables
Please refer complete article on Stock Buy Sell to Maximize Profit for more details!
Last Updated :
24 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...