Subarray with sum > 0 and length at least k
viaEngineBogie
Given an array arr containing only the values -1 and 1, and an integer k, determine whether there exists a subarray of length at least k whose elements sum to a value strictly greater than 0.
Input / Output
- Input: integer array
arr(each element is-1or1), integerk. - Output: boolean —
trueif such a subarray exists, otherwisefalse.
Constraints
1 <= arr.length <= 10^51 <= k <= arr.lengtharr[i]is either-1or1.
Example
arr = [-1, 1, 1, -1], k = 2→true(subarray[1, 1]has length 2 and sum 2 > 0).arr = [-1, -1, -1, 1], k = 2→false(no subarray of length >= 2 sums above 0).
Expected approach
- Build a prefix-sum array
pre, wherepre[i]is the sum of the firstielements. - A subarray ending at
jwith length>= khas positive sum iffpre[j] > min(pre[0 .. j-k]). - Sweep
jfromkton, keeping the running minimum ofpreover indices0 .. j-k; returntruethe momentpre[j]exceeds that minimum. - O(n) time, O(n) space.
asked …