KatInterview

Largest Sum in Any Consecutive Sequence

Dynamic ProgrammingAuto-graded · 21 test cases
MediumAuto-gradedDynamic Programmingarrayskadanesubarray

Last updated

Tests understanding of dynamic programming through finding the maximum sum achievable by selecting adjacent elements from an array.

Problem Statement

You are given an array of integers. Your task is to identify the consecutive sequence of elements whose sum is larger than any other consecutive sequence, and return that maximum sum.

The sequence must contain at least one element.

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • The answer will always fit within a 64-bit signed integer.

Notes

  • A consecutive sequence means elements that appear next to each other in the original array order.
  • When all elements are negative, the answer is the single largest (least negative) element.
  • You must select at least one element; the empty sequence is not allowed.

Examples

Example 1

Input: largest_consecutive_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4])

Output: 6

Example 2

Input: largest_consecutive_sum([-5, -1, -8])

Output: -1

Hints

Hint 1

Consider what happens at each position: should you extend the sequence you've been building, or start fresh from the current element?

Hint 2

Track two values as you scan left to right: the best sum ending exactly at the current position, and the overall best sum seen so far.

Hint 3

If carrying forward the previous sum would make things worse, it's better to reset and begin a new sequence at the current element.