Question:
Program to find maximum profit in a stock numbers, basically they will give a list of number basically it should be maximum profit.
example : [8,8,1,2,3,4,5,6,7,2,2]
So here user can buy a stock on low price – 1, even though 8 is present it won’t yield maximum since user cant sell at 8 and buy at 1, i will be loss. So expected answer is 1-7 = 6
-
Input:
-
array: A list of stock prices (e.g., [10, 7, 5, 8, 11, 9]).
-
-
Algorithm:
-
Initialize an empty list called result to store the profit differences.
-
Iterate over each low price in the array.
-
For each low price, iterate over each high price in the reversed array.
-
Check if the index of the low price is less than the index of the high price.
-
If true, calculate the profit (difference between high and low prices) and append it to the result list.
-
-
Output:
-
Print the maximum profit (the highest value in the result list).
-
For example, given the stock prices [10, 7, 5, 8, 11, 9], the maximum profit would be 6 (buy at 5, sell at 11).
Solution in python:
input = [10, 5, 20, 15, 30]
print(max_profit(input)) # Output: (25)
Preparing for interview?
-
Checkout our Interview prep page, It might help you.