Intuition
The problem asks for the maximum profit that can be achieved by buying and selling a stock. The idea is to find the optimal days to buy and sell to maximize the profit. If it is not possible to make a profit, the function should return 0.
Approach
The provided solution uses a two-pointer approach to iterate through the array and find the maximum profit.
Initialize two pointers, left and right, to represent the buying and selling days, respectively.
Initialize a variable maxp to keep track of the maximum profit.
While the right pointer is not at the end of the array:
Calculate the profit by subtracting the price on the buying day (prices[left]) from the price on the selling day (prices[right]).
Update maxp with the maximum of its current value and the calculated profit.
If the profit is greater than 0, move the right pointer to the next day.
If the profit is not greater than 0, reset the pointers to the current day and move them to the next day.
Return the maximum profit.
Complexity
- Time complexity:
The time complexity of this solution is O(n), where n is the length of the input array prices. The two-pointer approach allows for a single pass through the array.
- Space complexity:
The space complexity is O(1), as the solution uses only a constant amount of space to store pointers and variables.
Code
class Solution:
def maxProfit(self, prices: List[int]) -> int:
left,right = 0 , 1
maxp = 0
while right != len(prices):
profit = prices[right] - prices[left]
maxp = max(maxp,profit)
if profit > 0:
right+=1
else:
left = right
right+=1
return maxp