FastPrepMaximum Consecutive Sum Within a Threshold
Problems/Maximum Consecutive Sum Within a Threshold

Maximum Consecutive Sum Within a Threshold

Indeed logoIndeed● MediumNEW GRADOA
QuestionFunctionExamplesConstraints

Problem statement

Source note: The screenshot shows the full task from Indeed's online test. The test also asked for a short plan before coding and a complexity analysis after it. Those written parts are not judged here.

The original reads N and T from standard input and prints the answer. Here you get nums and threshold and return the answer. The original allows up to 1,000,000 numbers. Here the limit is 10^5 so the tests can reach it.

The judged task matches the source at about 95%.

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 as nums[i], nums[i + 1], ..., nums[j].
  • A sum equal to threshold is allowed.

Function

maximumSum(nums: int[], threshold: int) → int

Examples

Example 1

nums = [3,3,5,1,7]threshold = 10return = 9

The 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 = 0

Every 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 = 8

The 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^5
  • 0 <= nums[i] <= 10^9
  • 1 <= threshold <= 10^9

More Indeed problems

  • Insert into an Unrolled Linked ListPHONE SCREEN · ONSITE INTERVIEW · Seen Sep 2026
  • Course Completion OrderPHONE SCREEN · Seen May 2025
  • Recipes You Can PreparePHONE SCREEN · Seen May 2025
All Indeed interview questionsSee Indeed hiring insights
Saved
class Solution {
    public int maximumSum(int[] nums, int threshold) {
        // Write your code here.
    }
}
Checking account…