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& nums) { int min = nums.size() + 1; int sum = 0; int start = 0; for(int i=0; i= 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; } };
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}