Find max consecutive elements with sum below target
MicrosoftSoftware Engineer · Online AssessmentLast updated
This question evaluates algorithmic problem-solving with arrays, including reasoning about contiguous subsequences, handling sorted inputs and edge cases, and analyzing time and space complexity.
You are given:
- An integer array
numsof lengthn, sorted in non-decreasing order. - An integer
indexsuch that0 ≤ index < n. - An integer
target.
Starting from position index, you may take a contiguous sequence of elements going to the right:
nums[index], nums[index + 1], ..., nums[index + k - 1] for some integer k ≥ 0.
You want the sum of the chosen elements to be strictly less than target:
[ \sum_{i=index}^{index + k - 1} nums[i] < target. ]
Find the maximum possible value of k (the maximum number of consecutive elements starting from index whose sum is < target). If even nums[index] ≥ target, then the answer should be 0.
Design an efficient algorithm to compute this maximum k.
You may assume:
1 ≤ nnumsis sorted in non-decreasing order.
Describe the algorithm you would implement and its time and space complexity.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.