The cost of a stock on each day is given in an array. Find the maximum profit that you can make by buying and selling on those days. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all.

0

The cost of a stock on each day is given in an array. Find the maximum profit that you can make by buying and selling on those days. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all.

The cost of a stock on each day is given in an array. Find the maximum profit that you can make by buying and selling on those days. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all.

Cpp Program Code:



Explanation:

We use a vector to store the input array of prices. Then, we initialize two variables - max_profit and min_price. We iterate through the array and update these variables based on the current price.


For each price, we calculate the difference between the current price and the minimum price seen so far. If this difference is greater than the current maximum profit, we update max_profit. We also update min_price to be the minimum of the current price and the minimum price seen so far.


Finally, we print the maximum profit.



Python Program code:

Explanation:


We use a list to store the input array of prices. Then, we initialize two variables - max_profit and min_price. We iterate through the array and update these variables based on the current price.


For each price, we calculate the difference between the current price and the minimum price seen so far. If this difference is greater than the current maximum profit, we update max_profit. We also update min_price to be the minimum of the current price and the minimum price seen so far.


Finally, we print the maximum profit.




Post a Comment

0Comments
Post a Comment (0)