Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

How to solve the best time to buy and sell stock Problem in Java? LeetCode Solution Example

Hello guys, if you are preparing for coding interviews and looking for practice questions to sharpen your coding skill then you have come to the right place. In the past, I have shared 100+ data structure questions and 21 String Interview Questions and In Today's blog, we shall be looking at how to determine the best time to buy and sell stock. This is one of the popular coding problem from Leetcode as well so if you are looking for solution of Leetcode's Buy and Sell Stock problem then this tutorial can help you. Firstly, you have to note a few important things here as we solve this challenge, and one of them is an Array

All we shall be doing to tackle this problem evolves around the array and manipulations of it. We shall implement this task and then talk about the array and its operations but before we go on, We need to understand the nature of the problem. This would aid you in how you can manipulate it and do amazing pieces of stuff around it.

To know the best time to buy and sell a stock, you have to be careful to see when you would buy at a cheaper rate and sell at a higher rate so that you may have profit and not lost.

For example, Grace is a businesswoman that sells cookies and there is already a stated price for each day. If she buys a cookie on a particular day at a set price, she must sell it on whichever day she decides with the set price for the day after the day she bought it.

She uses an array because she is dealing with numbers of elements, not one. So all her items are stored in a single container. An array is a collection of elements of the same value. when I say the same value it means that you can not find different kinds of elements or data types there.

You can see below that we only have an array of integers,(I mean  numbers). Which are the prices of cookies are stored.


·       She must sell the previous stock before she can buy another

·        She must sell in the upcoming days, not the current day she bought the stock.

We would be needing an array of prices for cookies like below:

int [] price = {5, 2,9,1,6,7}

How to solve Best Time to Buy and Sell Stock Problem in Java? Leetcode Solution

With the above well broken down explanation, I hope you now understand the problem. A good understanding of the problem gives a good solution. Now, let's go to the implementation in Java code. I have two different approaches to solving this problem. 

Approach 1 :
  1. public int getMaxProfit(int []prices){
  2. int maxProfit = 0;
  3. for (int i = 0; i < prices.length; i++) {
  4. for (int j = i+1; j <prices.length; j++) {
  5. maxProfit = Math.max(maxProfit,prices[j]-prices[i]);
  6. }
  7. }
  8. return maxProfit;
  9. }
Approach 2 :
  1. public int getMaxProfit(int []prices){
  2. int min = Integer.MAX_VALUE;
  3. int maxProfit = 0;
  4. for (int price : prices) {
  5. if (price < min) {
  6. min = price;
  7. }
  8. maxProfit = Math.max(maxProfit, price - min);
  9. }
  10. return maxProfit;
  11. }
Driver's class:
  1. public static void main(String[] args) {
  2. BestTimeToBuyAndSellStock bestTime = new BestTimeToBuyAndSellStock();
  3. int [] prices = {2,3,15,5,7};
  4. System.out.printf("The maximum profit is %s" ,bestTime.getMaxProfit(prices));
  5. }       

Code Explanation:

In Approach 1, there was a method named get max profit which took in an array of prices as a parameter. in line 2, there was a variable "max profit" of type int which was initialized to zero. This tells us that at that level or time we have no maximum profit yet.

But, later in future as we have maximum profit it shall be updated in there. Line 3 and line 4 ran two different for loops. in line 6 Math.max was used to get the maximum profit between the prices and saved it in the variable max profit that was initially created. This approach is a simple approach but now let us check the second approach.

In Approach 2, Only a loop was run. so I used an enhanced for loop. (You can use either the normal loop or enhanced whichever one you like is fine. They both do the same thing) Here, I created two variables of type int. the first one was "min" which I initialized with the equivalent value of Integer.max value. It's such a large value that's far larger than 0.

The second variable is still our max profit which was zero at that time too. line 4 ran the enhanced for loop and line 5, the if statement. meaning that, for each price in the array of prices, if the particular price is lesser than the min that was created, then the min variable should be updated to it, no longer the initial value that was there. then in line 8 Math.max was called to find the greatest and save it in the max profit variable that was created. line 10 returned the max profit.

[Solved] How to know the best time to buy and sell stock in Java? LeetCode Solution Example


That's all about  how to solve the best time to buy and sell stock problem in Java. In the driver’s class In line 2 The Instance of the class “Best time to Buy and Sell Stock ” was created and was instantiated. In line 3 array of prices was created and initialized to the following numbers (2,3,15,5,7). The method (get Max Profit ) was called in line 4 to give us results. With these two approaches, you can now determine the best time to buy and sell stock in fact, You could come up with more other ways.


 Other Data Structure and Algorithms  articles you may like

  • 5 Books to Learn Data Structure and Algorithms in-depth (books
  • How to reverse an array in Java? (solution)
  • 6 Dynamic Programming Courses for Programmers (best courses)
  • 75+ Coding Interview Questions for Programmers (questions)
  • How to remove duplicate elements from the array in Java? (solution)
  • How to implement a recursive preorder algorithm in Java? (solution)
  • 10 (Free) Data Structure Courses for Programmers (free courses)
  • Recursive Post Order traversal Algorithm (solution)
  • How to print leaf nodes of a binary tree without recursion? (solution)
  • 10 Best Online Courses to Crack Coding Interview  (courses)
  • Recursive InOrder traversal Algorithm (solution)
  • How to solve climbing array problem in Java? (solution)
  • Iterative PreOrder traversal in a binary tree (solution)
  • How to count the number of leaf nodes in a given binary tree in Java? (solution)
  • 10 Free Data Structure and Algorithm Courses for Programmers (courses)
  • 100+ Data Structure Coding Problems from Interviews (questions)

Thanks for reading this article so far. If you like this Buy and Sell stock problem solution in Java then please share it with your friends and colleagues. If you have any issues, please drop a note.

P. S. - If you want to learn more about Dynamic programming you can also checkout these popular Dynamic programming online courses for both beginners and experienced developers. It will help you revise key Dynamic programming concepts. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.