JavaScript Program to Find Maximum Profit by Buying and Selling a Share at Most Twice using Array
Last Updated :
27 Sep, 2023
A buyer buys shares in the morning and sells them on the same day. If the trader is allowed to make at most 2 transactions in a day, the second transaction can only start after the first one is complete (Buy->sell->Buy->sell). Given stock prices throughout the day, find out the maximum profit that a share trader could have made.
Input: price[] = {10, 22, 5, 75, 65, 80}
Output: 87
Trader earns 87 as sum of 12, 75
Buy at 10, sell at 22,
Buy at 5 and sell at 80
Input: price[] = {2, 30, 15, 10, 8, 25, 80}
Output: 100
Trader earns 100 as sum of 28 and 72
Buy at price 2, sell at 30, buy at 8 and sell at 80
There are different approaches to finding maximum profit by buying and selling a share at most twice:
Approach 1: Naive approach
In this approach, we are going to store the maximum possible profit of every subarray and solve the problem in the following two phases.
- Create a table profit[0..n-1] and initialize all values in it to 0.
- Traverse price[] from right to left and update profit[i] such that profit[i] stores maximum profit achievable from one transaction in subarray price[i..n-1]
- Traverse price[] from left to right and update profit[i] such that profit[i] stores maximum profit such that profit[i] contains maximum achievable profit from two transactions in subarray price[0..i].
- Return profit[n-1]
Example: This example shows the use of the above-explained approach.
JavaScript
function maxProfit(price, n) {
// Create profit array and
// initialize it as 0
let profit = new Array(n);
for (let i = 0; i < n; i++)
profit[i] = 0;
/* Get the maximum profit with
only one transaction
allowed. After this loop,
profit[i] contains maximum
profit from price[i..n-1]
using at most one trans. */
let max_price = price[n - 1];
for (let i = n - 2; i >= 0; i--) {
// Max_price has maximum
// of price[i..n-1]
if (price[i] > max_price)
max_price = price[i];
// We can get profit[i] by taking maximum of:
// a) previous maximum, i.e., profit[i+1]
// b) profit by buying at price[i] and selling at
// max_price
profit[i] = Math.max(profit[i + 1],
max_price - price[i]);
}
// Get the maximum profit with
// two transactions allowed
// After this loop, profit[n-1]
// contains the result
let min_price = price[0];
for (let i = 1; i < n; i++) {
// min_price is minimum price
// in price[0..i]
if (price[i] < min_price)
min_price = price[i];
// Maximum profit is maximum of:
// a) previous maximum, i.e., profit[i-1]
// b) (Buy, Sell) at (min_price, price[i]) and add
// profit of other trans. stored in profit[i]
profit[i] = Math.max(profit[i - 1],
profit[i] + (price[i] - min_price));
}
let result = profit[n - 1];
return result;
}
// Driver code
let price = [2, 30, 15, 10, 8, 25, 80];
let n = price.length;
console.log("Maximum Profit = " +
maxProfit(price, n));
OutputMaximum Profit = 100
Time complexity: O(n)
Auxiliary space: O(n)
Approach 2: Recursive Approach
In this approach, we have two choices: Buy/Sell this stock OR ignore it and move to the next one. Along with day, we also need to maintain a capacity variable which will tell us how many transactions are remaining and it will be of which type (Buy or Sell). According to that we will make recursive calls and calculate the answer. We can do at most 4 transactions (Buy, Sell, Buy, Sell) in this order.
Example: This example shows the use of the above-explained approach.
JavaScript
function f(idx, buy, prices, cap, n) {
if (cap == 0) {
return 0;
}
if (idx == n) {
return 0;
}
let profit = 0;
// You can either buy or not buy
if (buy == 0) {
profit = Math.max(
-prices[idx] + f(idx + 1, 1, prices, cap, n),
f(idx + 1, 0, prices, cap, n)
);
}
// You can either sell or not sell
else {
profit = Math.max(
prices[idx] + f(idx + 1, 0, prices, cap - 1, n),
f(idx + 1, 1, prices, cap, n)
);
}
return profit;
}
function maxtwobuysell(prices, n) {
return f(0, 0, prices, 2, n);
}
const arr = [2, 30, 15, 10, 8, 25, 80];
const size = arr.length;
console.log(maxtwobuysell(arr, size));
Time Complexity : O(2^N)
Auxiliary Space : O(N)
Similar Reads
JavaScript Program for Maximum Possible Sum of Products In this article, we will find and print the maximum possible sum of products in the JavaScript language. We have two arrays, inputArr1, and inputArr2. Both these arrays contain positive numbers and the length of both arrays is similar. We have to write the function where every element in inputArr1 h
4 min read
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 d
4 min read
Find the Maximum Product of Two Integers in the Array using JavaScript ? Given an array of integers, we need to find the maximum product of two integers in the array using JavaScript.Example:Input: arr[] = {4, 6, 8, -5, -4, 4} Output: 48, {6,8} Explanation: Maximum product is 48, which is obtained by multiplying the numbers 6 and 8 of the array.Here are some common appro
8 min read
Find the Contiguous Subarray with the Largest Product in a given Array of Integers using JavaScript The objective is to find a contiguous subarray (one in which the elements are adjacent) with the largest product of its elements given an integer array. There are several approaches to finding the contiguous subarray with the largest products using JavaScript which are as follows: Table of Content B
3 min read
Javascript Program for Maximum Product Subarray Given an array that contains both positive and negative integers, find the product of the maximum product subarray. Expected Time complexity is O(n) and only O(1) extra space can be used.Examples:Input: arr[] = {6, -3, -10, 0, 2} Output: 180 // The subarray is {6, -3, -10} Input: arr[] = {-1, -3, -1
4 min read
Find Maximum Profit for Products within Budget Given a 2D integer array product, where product[i] = [costi, profiti] represents the cost and profit of a product, respectively. Additionally, you have been given a 0-indexed integer array called budget[]. For each budget[i], the task is to find the maximum profit of a product whose cost is less tha
11 min read