Best Time to Buy and Sell Stock

In this tutorial we will learn how to deduct Best Time to Buy And Sell Stock To Get maximum profit. Below are some examples. This problem can be solved by various approaches.

Problem?

Given an array of N length, representing the process of the stocks on different days. The task is to find the maximum profit for buying and selling the stocks on different days using the transactions where at most one transaction is allowed. This is a part of Data Structure.

Best Time To Buy and Sell The Stock Examples

Implementations of the algorithms are following:

Approach 1

This problem can be solved by the greedy approach. To get the maximum profit first we have to buy the stock at the minimum price and then sell the price at the maximum price, so we get maximum profit.

Follow the below steps to implement this approach:

• Create a buy variable to store the buying price at minimum price. Initialize it to the first variable of the array.
• Create a max_profit variable to store the maximum profit.
• Compare the buy price and max_profit, if current max_profit is less the comparison then store the new comparison.

JavaScript:

``````
const arr = [13, 1, 4, 8, 10, 41 ,14, 20, 23, 36];

let buy = arr[0], max_profit = 0;

for(let i=0; i<arr.length; i++){
//get lower buy price
// get max_profit
}else if(arr[i]- buy > max_profit){
max_profit = arr[i] -buy
}
}

console.log(max_profit);
``````

40

Same approach is in Java

``````
public class Profit {

static int bestPrice(int[] arr){
int buy = arr[0];
int max_profit = 0;
for(int i=0; i<arr.length; i++){

//get lower buy price

// get max_profit
}else if(arr[i]- buy > max_profit){
max_profit = arr[i] -buy;
}

}
return max_profit;
}

public static void main(String[] args) {
int[] arr = {13, 1, 4, 8, 10, 41 ,14, 20, 23, 36};
System.out.println("Max Profit: " + bestPrice(arr));

}
}
``````

Max Profit: 40

Time Complexity: O(N)
Auxiliary Space: O(N)

The time complexity for the above approach in both languages is same which is O(N) and the Auxiliary space taken is O(1). It is the optimized solution for this problem. See more about is from here.

Thank you for visiting the tutorial. You can comment in the comment section below for any query or doubt. Also you can publish your content on here out of free.

Can You Solve the Problem Of Removing Duplicates From An Array In JavaScript?