3 years ago
Can be easily brute forced but time complexity is O(n^2) since there are two for loops
If we plot the first example, we get the following:
Remember this, we want our left pointer to always be at the minimum because we want to buy low, sell high
This means that whenever we see a new minimum, we update the left pointer. This is handled by the condition if prices[l] < prices[r]
For every element, we need to calculate the difference between that element and the minimum of all the values before that element and we are updating the maximum profit if the difference thus found is greater than the current maximum profit.
This is a two pointer solution and the value at the left pointer will only be updated whenever a new minimum is found
If not, at each iteration, the profit is calculated, and if the profit is greater than the max profit, the max profit variable is updated
| Time | Space | Explanation |
|---|---|---|
O(n) | O(1) |