Sliding Window is used for finding the length of a subarray or directly returning the subarray that meet certain conditions. (We can use a variable to track the length if returning the subarray is not needed.)
For problems involving the sum, product, or average of a subarray that must meet a target, both the Sliding Window and Prefix Sum approaches may be applicable.
O(n) complexity by expanding and contracting the window dynamically.O(n).https://leetcode.com/problems/best-time-to-buy-and-sell-stock
Last review: Aug 16, 2025 Next review: It was cool.
We must buy the stock first then sell it. We can not go back to the past to sell the stock earlier than the buying time.
Compare to ⭐️ (Medium) 122. Best Time to Buy and Sell Stock II, NeetCode 250 this question only allows buying and selling once.
When we find a better buying point, from there, we don’t need the the current buying price compare with future prices, cause it is better to use the better buying point to compare with.
O(n*(n+1)/2) = O(n^2)O(1)func maxProfit(prices []int) int {
var profit int
for L := 0; L < len(prices); L++ {
for R := L + 1; R < len(prices); R++ {
profit = max(profit, prices[R]-prices[L])
}
}
return profit
}
The window means the range we hole the stock:
O(n)