Maximum Consecutive Sum Within a Threshold
Problem statement
You are given an array nums of non-negative integers and an integer threshold.
Find the largest sum of consecutive elements of nums that does not exceed threshold, and return it. If every possible sum is larger than threshold, return 0.
- Consecutive elements means one or more elements that sit next to each other in
nums, such asnums[i], nums[i + 1], ..., nums[j]. - A sum equal to
thresholdis allowed.
Function
maximumSum(nums: int[], threshold: int) → intExamples
Example 1
nums = [3,3,5,1,7]threshold = 10return = 9The block 3, 5, 1 (indices 1 to 3) adds up to 9. No block of neighbors adds up to exactly 10: 3 + 3 + 5 = 11 and 5 + 1 + 7 = 13 are too large, so 9 is the best sum that stays within the threshold.
Example 2
nums = [4,8,2]threshold = 1return = 0Every number is larger than 1, so every block of consecutive numbers goes over the threshold. There is no valid sum, so the answer is 0.
Example 3
nums = [2,7,1,4,3]threshold = 8return = 8The block 7, 1 adds up to exactly 8. A sum equal to the threshold is allowed, and no sum can be larger than the threshold, so the answer is 8.
Constraints
1 <= nums.length <= 10^50 <= nums[i] <= 10^91 <= threshold <= 10^9