DEV Community

Debesh P.
Debesh P.

Posted on

209. Minimum Size Subarray Sum | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/minimum-size-subarray-sum/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/minimum-size-subarray-sum/solutions/7460220/most-optimal-solution-ever-beats-100-sli-39e0


leetcode 209


Solution

class Solution {
    public int minSubArrayLen(int target, int[] nums) {

        int n = nums.length;
        int sum = 0;
        int left = 0;
        int ans = n + 1;

        for (int right = 0; right < n; right++) {
            sum += nums[right];

            while (sum >= target) {
                ans = Math.min(ans, right - left + 1);
                sum -= nums[left];
                left++;
            }
        }

        return ans == n + 1 ? 0 : ans;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)