122. Best time to buy and sell stocks - 2 | Leetcode

Опубликовано: 20 Апрель 2026
на канале: AbIn
258
8

There exist various approaches to address this inquiry; however, the most optimal solution entails employing a one-pass algorithm.

The proposed solution involves purchasing a stock if its price on the preceding day is lower than the current day's price. By acquiring the stock at the previous price and subsequently selling it on the current day, a profit is realized. By repeating this process for all instances where the current price exceeds that of the previous day, the cumulative profits can be aggregated.

For illustrative purposes, consider the input array 'prices' with values [7, 1, 5, 3, 6, 4]. The array indexes denote the respective days. For instance, on day 2, the current price is 5, whereas on the previous day (day 1), the price amounts to 1. This configuration satisfies our stipulated condition, resulting in a profit of 5-1 = 4. Similarly, on day 4, the current price is 6, while the preceding day (day 3) records a price of 3. Once again, this aligns with our criteria, yielding a profit of 6-3 = 3. No other consecutive day pairs satisfy the condition prices[i - 1] is less than prices[i]. Consequently, the total profit amounts to 4 + 3 = 7.

The time complexity of this solution is O(N), where N represents the length of the input price array. Moreover, the space complexity remains constant at O(1).

0:00 - Introduction
2:26 - Explanation
5:20 - Coding the solution

Link to part 1:    • 121. Best time to buy and sell stocks - 1 ...  
#leetcode #datastructures #interviewquestions