Javascript Program For Stock Buy Sell To Maximize Profit
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:
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>
|
Output:
865
Time Complexity: O(N2)
Auxiliary Space: O(1)
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.
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>
|
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)
Space Complexity: O(1) since using constant variables
Please refer complete article on Stock Buy Sell to Maximize Profit for more details!
Last Updated :
10 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...