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.
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!
Find Two Sum Leetcode Solution
Reverse a Linked List in Python
Inheritance in OOPs: Ultimate Guide for Coding Interviews
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 follow web page
Program : best time to buy and sell stock
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.
Follow webpage to get steps how it is works.
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;
}
Top comments (0)