|
U
Pro45. Longest Subarray with Sum K (Non-negative Numbers)
Med.
Problem Description
Given an array of N non-negative integers and a target K, find the length of the longest contiguous subarray whose sum equals K. If no such subarray exists, print 0.
Input Format
- •Line 1: Two space-separated integers N and K (1≤N≤105, 0≤K≤109).
- •Line 2: N space-separated non-negative integers A1,…,AN.
Output Format
Print the length of the longest contiguous subarray whose sum is K.
Example 1:
Input:
5 5 1 2 3 1 1
Output:
3
Explanation: Subarray [3, 1, 1] has sum 5 and length 3.
Example 2:
Input:
3 10 1 2 3
Output:
0
Explanation: Total array sum is 6 < 10; output 0.
Example 3:
Input:
4 0 0 0 0 0
Output:
4
Explanation: Entire array of zeros has sum 0 and length 4.
Constraints:
Standard integer bounds: 32-bit signed integer or input range [1, 10^5].Time complexity target: O(N) or O(N log N) where applicable.Auxiliary space target: O(1) or minimal auxiliary memory.
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online
Code
|Loading Code Editor...
SavedLn 1, Col 1
param_1 =
param_2 =
Sandboxed Engine
Ctrl+Enter = Run | Ctrl+Shift+Enter = Submit