Let’s find the optimal solution for the ‘**Best Time to Buy and Sell Stock**‘ problem, as presented by LeetCode, GeeksforGeeks, Coding Ninjas, and CodeStudio. The answer should be consistent across these platforms.

Welcome back visitors! In this blog post, I am diving into the solution for the ‘Best Time to Buy and Sell Stock’ program. This program is trending on platforms like LeetCode, GeeksforGeeks, Coding Ninjas, and CodeStudio. Understanding this is crucial in the world of programming, as it is a commonly asked question.

**FREE** : If you’re a new visitor preparing for an interview and need help or **want to request a new question**, you can use **the form on the right side to ask your question**.** It’s free and doesn’t require signing in**. Alternatively, you can ask in our **Quora space**, which is also **free**, and you’ll receive **a response within 24** hours. Go ahead and check it out!

## Table of Contents

## Understand Question : best time to buy and sell stock program

I believe you’ve already read this question and attempted to solve it. Am I correct? If not, don’t worry.

Firstly, let’s address the question itself, because without understanding what we need to find or solve, we won’t be able to implement anything.

The interviewer will ask you a question where they aim to achieve maximum profit from N number of days. This implies that you need to buy a stock or share at a minimum price range X and sell it at a maximum price Y within the given N number of days.

To illustrate that, check the image below.

## Logic behind : best time to buy and sell stock

Let’s dive into the solution part of the ‘best time to buy and sell stock’ question from a programming perspective.

As we discussed in the ‘Understand Question’ section, the interviewer will provide you with N number of elements, which means you’ll have **an array**. Your task is to find the minimum stock or share price, **X**, and sell that stock or share for a maximum profit of **Y**. This means you may need three things to start the logic. Do you understand?

Now that we have the required entities to start building the logic, firstly, you need to have a loop to iterate through each element in the array, am I correct? Then, you have to find the minimum number. Therefore, in each iteration, you have to add a condition to check the next element’s size. In other words, you have to check if the current element’s price is smaller than the next element, then set the next element to the current element.

By doing that, you would have the minimum stock price to buy.

Next, this is the main part of the logic: when you find the profit price, in other words, you will find the maximum number from the array of N numbers.

To accomplish this, add a check where you subtract the current element by our minimum X value. If this result is higher than our last profit value, then set that value to the profit.

By doing so, you would have the maximum profit from that given array or the array of given days. check the illustration below, which represents how the solution for the best time to buy and sell stock will work.

## Program : best time to buy and sell stock

I’m going to break down this logic into three separate steps so we can understand it easily. If you find the logic difficult to understand on your own, feel free to check out our **Beginner** and **Pyramid** programs first. There, I have explained how to create your own logic from a given question or definition.

### Step 1

I know you’re a regular visitor and you’ve started our first logic implementation. Good to know that. If you’re a new visitor, then the first step is to create the required variables to start with. If you have no idea where to start, check the explanation section,

There I’ve mentioned having an array of days, where each element contains the stock or share price, and each element represents a day. We have to find the minimum buy price, so I’m going to create a variable named ‘minBuyPrice’. Additionally, we need to find the maximum profit amount, so I’m going to add a variable named ‘profit’.

Next, I am going to assign our first element of array to base buy or minimum buy amount.

```
static void Main()
{
int[] prices = new int[] { 7, 1, 5, 3, 6,};
Console.WriteLine(MaxProfit(prices));
}
static int MaxProfit(int[] prices)
{
int profit = 0;
int minBuyPrice = prices[0];
return profit;
}
```

### Step 2

Secondly, to retrieve each element from the array, I’ll add a for loop starting with the second element of the given array. In the ‘best time to buy and sell stock program’, our first element represents the first day with the minimum buy amount. Therefore, our loop will start with index 1 instead of 0. Do you understand?

```
static int MaxProfit(int[] prices)
{
int profit = 0;
int minBuyPrice = prices[0];
for (int i = 1; i < prices.Length; i++)
{
}
return profit;
}
```

### Step 3

This is our final step to find the solution to the best time to buy and sell stock program, and I’m going to divide it into smaller subsections so you can grasp this logic well

#### Find Minimum Buy Price

Our first goal is to locate the minimum buy price for the stock or share. Therefore, I’m going to create a local variable called ‘currentDayPrice’ and use a conditional statement to check if ‘currentDayPrice’ is less than our ‘minBuyPrice’. If it is, we assign ‘minBuyPrice’ to ‘currentDayPrice’.

And most importantly, if we’ve found the ‘minBuyPrice’, then we use the ‘continue’ statement to jump to the next iteration of our loop. In the next section, you’ll understand why it’s necessary to use this. Stay with us.

```
static int MaxProfit(int[] prices)
{
int profit = 0;
int minBuyPrice = prices[0];
for (int i = 1; i < prices.Length; i++)
{
int currentDayPrice = prices[i];
if (currentDayPrice < minBuyPrice)
{
minBuyPrice = currentDayPrice;
continue;
}
}
return profit;
}
```

#### Find Maximum Profit Price

Now, our final step is to search for the maximum profit to find the ‘Best Time to Buy and Sell Stock Solution’.

By implementing the logic in the above section, we can find the minimum stock price and successfully set it to ‘minBuyPrice’. Now, the question is, what if we are unable to locate the minimum buy price in a certain iteration? Am I correct?

The answer is straightforward: if the value of the current iteration is not our minimum buy price, then it must be our profit price. In other words, it would be our maximum price to sell the stock or share. Therefore, I’m going to add a conditional statement to check if ‘currentDayPrice’ subtracted by ‘minBuyPrice’ is greater than our ‘profit’. If it is, we simply update our ‘profit’. Understood?

```
static int MaxProfit(int[] prices)
{
int profit = 0;
int minBuyPrice = prices[0];
for (int i = 1; i < prices.Length; i++)
{
int currentDayPrice = prices[i];
if (currentDayPrice < minBuyPrice)
{
minBuyPrice = currentDayPrice;
continue;
}
if ((currentDayPrice - minBuyPrice) > profit)
{
profit = currentDayPrice - minBuyPrice;
}
}
return profit;
}
```

This marks the end of our program to find the solution for the Best Time to Buy and Sell Stock. Now you can use this logic to solve questions on platforms like LeetCode, GeeksforGeeks, Coding Ninjas, and CodeStudio.

## Summarizing Best time to buy and sell stock Solution

We tackled the problem of finding the best time to buy and sell stocks, a common challenge found on platforms like LeetCode, GeeksforGeeks, Coding Ninjas, and CodeStudio. The solution involves iterating through an array of stock prices to determine the minimum buy price and the maximum profit that can be achieved.

- Locating the minimum buy price by iterating through the array and updating the ‘minBuyPrice’ variable accordingly.
- Continuing the loop if the minimum buy price is found, using the ‘continue’ statement.
- Searching for the maximum profit by comparing the difference between each day’s price and the minimum buy price, updating the ‘profit’ variable if a higher profit is found.

This solution provides a clear and efficient approach to solving the ‘Best Time to Buy and Sell Stock’ problem, which can be applied across various programming platforms and interview scenarios.