Home Minimum Size Subarray Sum
Post
Cancel

LeetCode #209: Minimum Size Subarray Sum (C/C++).

medium

source: https://leetcode.com/problems/minimum-size-subarray-sum/
C/C++ Solution to LeetCode problem 209. Minimum Size Subarray Sum.

Problem


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 subarray, return 0 instead.

Examples


Example 1:

Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.

Example 2:

Input: target = 4, nums = [1,4,4]
Output: 1

Example 3:

Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0

Constraints


  • 1 <= target <= 109
  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 104

Solution


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
  int minSubArrayLen(int target, vector<int>& nums) {
    int min = nums.size() + 1;
    int sum = 0;
    int start = 0;

    for(int i=0; i<nums.size(); i++) {
      sum += nums[i];
      while (sum >= target && start < i) {
        if (sum - nums[start] >= target) {
          sum -= nums[start];
          start += 1; 
        }
        else
          break;
      }
      int s = (i+1) - start;
      if (sum >= target && s < min)
        min = s;   
    }
      
    return min == nums.size() + 1 ? 0 : min;
  }
};
This post is licensed under CC BY 4.0 by the author.

-

Product of Array Except Self