KatInterview

Highest-Yield Consecutive Stretch in a Profit Log

Dynamic ProgrammingAuto-graded · 20 test cases
MediumAuto-gradedDynamic Programmingkadanesubarraydynamic-programming

Last updated

Find the largest total achievable by a non-empty run of adjacent integers, handling all-negative inputs and large sums, in one pass with constant extra space.

Best Consecutive Stretch

A analytics team records the net change of a metric for each day in a list of integers called daily_changes. They want to know the strongest possible result from looking at one unbroken run of days.

Write a function that returns the largest total obtainable by adding up the values in a non-empty block of adjacent entries of the list.

Details

  • A block is a sequence of consecutive positions i, i+1, ..., j with i <= j.
  • The block must contain at least one element, so an empty block (total 0) is never a valid answer.
  • If every value is negative, the answer is the single largest (least negative) element.
  • If the list has one element, the answer is that element.
  • Totals can be far larger than a 32-bit integer; Python integers handle this natively, but your logic should not assume small sums.

Aim for a solution that runs in linear time and uses only constant extra memory.

Input

  • daily_changes: a list of integers.

Output

  • An integer: the maximum sum over all non-empty contiguous blocks.

Constraints

  • 1 <= len(daily_changes) <= 10^5
  • -10^9 <= daily_changes[i] <= 10^9

Examples

Example 1

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

Output: 6

Example 2

Input: best_consecutive_stretch([-5, -2, -8, -1, -4])

Output: -1

Hints

Hint 1

For each position, consider only the best block that ends exactly there. How can that be built from the best block ending one position earlier?

Hint 2

At each element you either extend the previous block or begin a new block at this element. When is starting fresh the better option?

Hint 3

Initialize your running values from the first element instead of 0, so that an all-negative list does not wrongly return 0.