Stock Buy and Sell ProblemIntroduction to the ProblemYou are given an array named prices, where the ith index stores the price of a stock on the ith day. The problem involves determining the best times to buy and sell stocks to maximize profit. This problem was asked in SDE Interviews by Amazon, Microsoft, DE Shaw, Paytm, Google, Walmart, and others. Example 1 Example 2 The goal is to find the maximum possible profit that we can obtain by buying and selling the stock within this period. However, there are a few constraints that need to be followed:
Problem - Find the Maximum ProfitIn general, we will be asked to Find the Maximum Profit only. In this case, we can use a simple greedy approach.
Python Code:Output: C++ Code:Output: C Code:Output: Problem - Find the Best Day to Buy and Sell the Stock to Maximize the Profit.This problem is trickier than finding the profit only. In this problem, we are asked to find the segments of days on which we can buy and sell the stock to generate maximum profit. Considering the first example discussed above: In this problem, we will return a list containing segments of days, [(0, 3), (4, 5)], on which we can buy and sell the stock. This problem can be solved by determining the difference between local maximum and local minimum and summing up the profit. Special Cases:
The algorithm can be summarized as follows:
Python Code:Output: Explanation: In the above program, we iterate through all prices using a while loop. We first find the index of the local minimum and store it in the buy_on variable. We then search for the local maximum, and if found, we store it in the sell_on variable. We then store buy_on and sell_on in the segments_of_days list. After finding all the possible segments, we return the answer. C++ Code:Output: C CodeOutput: Note - C code includes memory allocation and deallocation for the dynamic array of segments using realloc() and free() functions, respectively.CONCLUSION:The stock buy and sell coding problem is often solved using various algorithms such as brute force, dynamic programming, and greedy algorithms. The optimal solution depends on the specific requirements and constraints of the problem at hand. The greedy approach is used to solve both variations. In the first variation, we iterate through the prices and calculate the profit by taking the difference between the current and previous prices whenever the current price is higher. In the second variation, we find segments of days where the stock should be bought and sold to generate maximum profit. Overall, the stock buy and sell problem is a common algorithmic problem asked in interviews by major companies and can be efficiently solved using a greedy approach. Next TopicFind Minimum in Rotated Sorted Array |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India