Skip to content

0209: Minimum size subarray sum #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions 0209-Minimum_Size_Subarray_Sum/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// let target = 7,
// nums = [2, 3, 1, 2, 4, 3];
// let target = 4,
// nums = [1, 4, 4];
let target = 11,
nums = [1, 1, 1, 1, 1, 1, 1, 1];

function miniSubArrayLen(target: number, nums: number[]): number {
let left: number = 0,
right: number = 0;
let res: number = nums.length + 1;
let sum: number = 0;
while (right < nums.length) {
sum += nums[right];
if (sum >= target) {
while (sum - nums[left] >= target) {
sum -= nums[left++];
}
res = Math.min(res, right - left + 1);
}
right++;
}
return res === nums.length + 1 ? 0 : res;
}

let result = miniSubArrayLen(target, nums);
console.time("miniSubArrayLen");
miniSubArrayLen(target, nums);
console.timeEnd("miniSubArrayLen");

console.log(result);
27 changes: 27 additions & 0 deletions 0209-Minimum_Size_Subarray_Sum/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# 209. Minimum Size Subarray Sum

Given an array of positive integers `nums` and a positive integer `target`, return <i>the <b>minimal length</b> of a
<span style="color: #007ef9;" title="A subarray is a contiguous non-empty sequence of elements within an array.">subarray</span>
whose sum is greater than or equal to</i> `target`. If there is no such subarray, return `0` instead.

## Example 1:

> <span style="color: white;">Input: </span>target = 7, nums = [2, 3, 1, 2, 4, 3]<br>
> <span style="color: white;">Output: </span>2<br>
> <span style="color: white;">Explanation: </span>The subarray [4, 3] has the minimal length under the problem constraint.

## Example 2:

> <span style="color: white;">Input: </span>target = 4, nums = [1, 4, 4]<br>
> <span style="color: white;">Output: </span>1

## Example 3:

> <span style="color: white;">Input: </span>target = 11, nums = [1, 1, 1, 1, 1, 1, 1, 1]<br>
> <span style="color: white;">Output: </span>0

### Constraints:

- 1 <= target <= 10<sup>9</sup>
- 1 <= nums.length <= 10<sup>5</sup>
- 1 <= nums[i] <= 10<sup>4</sup>