AlgoTales · Roadmap

Maximum sum problems

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Maximum sum problems look for the best total from a run of values, such as the best stretch of consecutive days. The key idea is to keep a running total and drop it if it turns negative. It is the standard way to answer "when was the best period?".

Practical use cases

  • Web app: Best week in daily sales. An admin dashboard shows daily profit and losses for a year, and the owner asks "which stretch of days made the most money in a row?". The code walks through the days, adds each to a running total, and restarts when the total is below zero. The best stretch is found in one pass over 365 values. A manager can now click "show best stretch" and see highlighted dates, instead of scrolling through a chart and guessing.
  • Web app: Cricket or stock streak highlights. A sports stats site highlights the best consecutive run of a batter's scores above their usual average, and a trading practice app does the same for gains. Both keep the best run seen so far while scanning once. Because it needs only one pass, the page can update the highlight live as each new match or trading day is added to the data.
  • System: Signal processing and genome scanning. Scientists look for the strongest stretch of a signal or a gene region. Scanning once while dropping stretches that are losing is much faster than checking every start and end pair. In each of these, a single left-to-right scan that drops a losing stretch and restarts is enough, which makes it cheap even for millions of readings.

The story: Raju's Best Stretch

Raju kept a tiny diary of his stall's money, day after day: a profit of 2 rupees, then a loss of 4, then profits of 3 and 5, a small loss of 2, and so on. His nephew Aarav asked: "In which unbroken run of days did you earn the most in total?" It had to be consecutive days, no skipping.

Aarav tried every starting day and every ending day. That was a lot of adding. Mira found the neat way: go day by day and keep just one number, the best total of a run that ends today. For each new day there are only two choices: extend yesterday's run (if it is worth something positive) or start fresh today (if yesterday's run is dragging you down).

"Why would I carry a bad run along?" said Mira. "If yesterday's run has a negative total, throw it away. It only makes today worse." So today's best = today's amount + (yesterday's best, but only if it is positive). While walking, remember the biggest number ever seen.

This is the heart of maximum sum problems: the best total of a run, or of a chosen group, built up one step at a time. This particular puzzle is the famous maximum subarray (Kadane's idea). Last lesson's house robber, picking the best non-neighbour sum, is a cousin from the same family.

How to spot this problem, and where you need it

You have a list of positive and negative numbers in order and want the contiguous stretch with the biggest total, without checking every possible start and end.

Signs you need it

  • The problem says "contiguous", "consecutive", "subarray" or "best period" with numbers that can be negative.
  • Your first solution has two nested loops for start and end, and it slows sharply on long histories.
  • Adding up everything would not work because bad days in the middle drag the total down.

Where to use it in a project

  • Finding the best or worst stretch in daily revenue, traffic or profit reports.
  • Highlighting streaks in sports, analytics or finance dashboards.

The solution

Walk through the numbers once. Keep a running total of the stretch that ends at the current item: it is either the item alone (start fresh) or the item added to the previous running total, whichever is bigger. Also keep the biggest running total seen so far. When the running total falls below zero it is dragging you down, so effectively start over. At the end, the biggest value is your answer.

Payoff: Before: about 66,000 checks for 365 days with nested loops. After: 365 steps in one loop.

Explain it like I am 8

You are rolling a snowball down a hill. If the snowball is big and good, keep rolling it and add more snow. If it has become a pile of mud, drop it and start a fresh clean snowball. Always remember the biggest clean snowball you ever had.

How it works, step by step

  1. State: dp[i] = the best total of a run that ends exactly on day i.
  2. Base case: dp[0] = a[0].
  3. Transition: dp[i] = a[i] + max(0, dp[i-1]). Extend if yesterday was positive, restart otherwise.
  4. The answer is the biggest dp[i] anywhere (not necessarily the last).
  5. Family idea: other "maximum sum" puzzles (non-adjacent picks, best pair, best path) all follow the same recipe: define the state, then take the best among a few last moves.

The code in four languages

PHP

<?php
// Maximum sum of a run of consecutive days (maximum subarray).
// $cur = best total of a run that ENDS on the current day.
function bestStretch(array $a): array {
    $cur = $a[0];
    $best = $a[0];
    $start = 0; $bestStart = 0; $bestEnd = 0;
    for ($i = 1; $i < count($a); $i++) {
        if ($cur > 0) {
            $cur += $a[$i];                     // extend: yesterday's run is a help
        } else {
            $cur = $a[$i];                      // start fresh: yesterday's run is a burden
            $start = $i;
        }
        if ($cur > $best) { $best = $cur; $bestStart = $start; $bestEnd = $i; }
    }
    return [$best, $bestStart, $bestEnd];
}

[$best, $from, $to] = bestStretch([2, -4, 3, 5, -2, 4, -9, 6]);
echo "Best total ", $best, " from day ", $from + 1, " to day ", $to + 1, "\n";   // 10, days 3 to 6
print_r(bestStretch([-3, -1, -2]));              // [-1, 1, 1]: all losses, so the least bad day

JavaScript

// Maximum sum of a run of consecutive days (maximum subarray).
// cur = best total of a run that ENDS on the current day.
function bestStretch(a) {
  let cur = a[0], best = a[0];
  let start = 0, bestStart = 0, bestEnd = 0;
  for (let i = 1; i < a.length; i++) {
    if (cur > 0) {
      cur += a[i];                              // extend: yesterday's run is a help
    } else {
      cur = a[i];                               // start fresh: yesterday's run is a burden
      start = i;
    }
    if (cur > best) { best = cur; bestStart = start; bestEnd = i; }
  }
  return [best, bestStart, bestEnd];
}

const [best, from, to] = bestStretch([2, -4, 3, 5, -2, 4, -9, 6]);
console.log("Best total " + best + " from day " + (from + 1) + " to day " + (to + 1));   // 10, days 3 to 6
console.log(bestStretch([-3, -1, -2]));          // [ -1, 1, 1 ]: all losses, so the least bad day

Java

import java.util.*;

public class Main {
    // Maximum sum of a run of consecutive days (maximum subarray).
    // cur = best total of a run that ENDS on the current day.
    // Returns {best total, first day, last day} (days counted from 0).
    static int[] bestStretch(int[] a) {
        int cur = a[0];
        int best = a[0];
        int start = 0, bestStart = 0, bestEnd = 0;
        for (int i = 1; i < a.length; i++) {
            if (cur > 0) {
                cur += a[i];                        // extend: yesterday's run is a help
            } else {
                cur = a[i];                         // start fresh: yesterday's run is a burden
                start = i;
            }
            if (cur > best) { best = cur; bestStart = start; bestEnd = i; }
        }
        return new int[]{best, bestStart, bestEnd};
    }

    public static void main(String[] args) {
        int[] r = bestStretch(new int[]{2, -4, 3, 5, -2, 4, -9, 6});
        System.out.println("Best total " + r[0] + " from day " + (r[1] + 1) + " to day " + (r[2] + 1));   // 10, days 3 to 6
        System.out.println(Arrays.toString(bestStretch(new int[]{-3, -1, -2})));   // [-1, 1, 1]: all losses, so the least bad day
    }
}

Go

package main

import "fmt"

// Maximum sum of a run of consecutive days (maximum subarray).
// cur = best total of a run that ENDS on the current day.
// Returns the best total and the first and last day (counted from 0).
func bestStretch(a []int) (int, int, int) {
	cur, best := a[0], a[0]
	start, bestStart, bestEnd := 0, 0, 0
	for i := 1; i < len(a); i++ {
		if cur > 0 {
			cur += a[i] // extend: yesterday's run is a help
		} else {
			cur = a[i] // start fresh: yesterday's run is a burden
			start = i
		}
		if cur > best {
			best, bestStart, bestEnd = cur, start, i
		}
	}
	return best, bestStart, bestEnd
}

func main() {
	best, from, to := bestStretch([]int{2, -4, 3, 5, -2, 4, -9, 6})
	fmt.Printf("Best total %d from day %d to day %d\n", best, from+1, to+1) // 10, days 3 to 6
	fmt.Println(bestStretch([]int{-3, -1, -2}))                             // -1 1 1: all losses, so the least bad day
}

Time: O(n) · Extra space: O(1). One pass and two running numbers. Checking every start and end pair by brute force would be O(n²) or worse.

Watch out for

  • Starting the best at 0, which silently allows an empty stretch. If all days are losses the answer should be the least bad single day.
  • Taking the last dp value as the answer. The best run may end earlier; keep a separate "best so far".
  • Confusing "run of consecutive days" (this lesson) with "any chosen days with no neighbours" (house robber). Different rules, different transitions.

Quick check

  1. When yesterday's best run ending total is negative, what should today do?
    • Add it anyway
    • Start fresh with just today's amount
    • Stop the whole algorithm
  2. Where do you read the final answer?
    • The last dp box only
    • The first dp box
    • The biggest dp box seen anywhere
  3. Days: 4, -1, 2, -7, 3. Best total of a consecutive run?
    • 5
    • 6
    • 3