209. Minimum Size Subarray Sum
Tags:
Medium
Skills:
Sliding Window
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Bạn cần tìm độ dài nhỏ nhất của một đoạn con liên tục trong mảng nums sao cho tổng của đoạn con đó ≥ target. Nếu không tồn tại đoạn con thỏa mãn, return 0
Approach - sliding window
left và right để xác định cửa sổ hiện tạiright để tăng tổng, khi tổng ≥ target thì thử thu nhỏ cửa sổ bằng cách tăng left để tìm cửa sổ nhỏ nhất vẫn thỏa mãnTime and space complexity
Solution
1function minSubArrayLen(target: number, nums: number[]): number {
2 let left = 0;
3 let current_sum = 0;
4 let min_len = Infinity;
5
6 for (let right = 0; right < nums.length; right++) {
7 current_sum += nums[right];
8 while (current_sum >= target) {
9 min_len = Math.min(min_len, right - left + 1);
10 current_sum -= nums[left];
11 left++;
12 }
13 }
14
15 return min_len === Infinity ? 0 : min_len;
16};