Maximum Subarray IV
(Largest sum subarray with at-least k numbers)
Description
Given an integer arrays, find a contiguous subarray which has the largest sum and length should be greater or equal to given lengthk
.
Return the largest sum, return 0 if there are fewer than k elements in the array.
Ensure that the result is an integer type.
Example
Given the array[-2,2,-3,4,-1,2,1,-5,3]
and k =5
, the contiguous subarray[2,-3,4,-1,2,1]
has the largest sum =5
.
Analysis
这一题跟之前的Maximum subarray sum有一些区别,Kadane Algorithm不是能很好的应用这这里。
在于求解区间和时要求了区间的长度大于等于k。
maxSum的基准是前k个元素之和;前缀和的最小值minPrefix在取用的时候需要比较的是sum[i - k]
也就保证了maxSum的取值的区间长度至少是k (sum[i] - sum[i - k], i - (i - k) = k)。
Solution
(455 ms beats 82.80%)
Another one
Reference
[Maximum Subarray IV](https://gpp676.wordpress.com/2017/10/13/maximum-subarray-iv/
GeeksforGeeks: https://www.geeksforgeeks.org/largest-sum-subarray-least-k-numbers/
Last updated
Was this helpful?