[LeetCode] 209번: Minimum Size Subarray Sum - Java

2023. 2. 17. 19:46Computer Sciences/Problem Solve

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

 

Minimum Size Subarray Sum - LeetCode

Can you solve this real interview question? Minimum Size Subarray Sum - Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarr

leetcode.com

문제 설명

타겟 넘버와 양수로 구성된 배열이 주어진다. 이때 배열의 요소의 조합 중 타겟 넘버보다 크거나 같은 요소 조합 중 요소가 가장 적은 조합의 요소 개수를 구하면 된다.

풀이 방법: 투 포인터 - O(n)

아래 풀이로 풀 수 있는 데는 숫자가 모두 양수라는 조건이 있어서다. 만약 음수가 포함되어 있다면 아래 12행에서 sum -= nums[start++] 에서 음수가 양수로 바뀌어버릴 수도 있기 때문이다.

public int minSubArrayLen(int target, int[] nums) {
    if (nums == null || nums.length == 0)
        return 0;

    int sum = 0, start = 0, end = 0, ans = Integer.MAX_VALUE;

    while (end < nums.length) {
        sum += nums[end++];

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

    return ans == Integer.MAX_VALUE ? 0 : ans;
}