Find Max Profit By Buying And Selling Stock

In the given problem, we are provided with an array named "prices," where prices[i] represents the current price of a stock on day i. The task is to determine the maximum profit that can be achieved from selling the stock. This problem can be found in leetcode at this link .

This problem differs from the yesterdays problem in the sense that here we can buy and sell multiple times and multiple stocks, but we can only hold one stock at any given time.

Solution: Solution

class Solution: def maxProfit(self, prices: List[int]) -> int: maxprofit = 0 for i in range(1,len(prices)): if prices[i]>prices[i-1]: maxprofit += prices[i]-prices[i-1] return maxprofit

Apparantly, the max profit that you can make in situations like this is if you frequently keep selling the stocks, i.e, the max profit is the sum of differences of consecutive values if the next value is higher than the previous value. In the above solution, no matter when you buy or sell a stock, the profit to be made is captured by the sum if we account for the difference in our profit as soon as the price increases.

The above solution beats 100% of the submission in leetcode.