cswork / templatesOpen the Line 500 list

STOP 28 · DYNAMIC PROGRAMMING

State Machines and Contiguous Sequences

Ending-at-i states: track both max and min O(n) time · O(1) space

Contest ratings Rating 1602–Rating 1799· median Rating 1786(5 of 6 problems rated by zerotrac)

Open the Line 500 list · stop 28 · 6 problems
Learn first
Leads to
How often asked
asked by 1 company · in 1 reportTikTok / ByteDance 1

Warm up with this one

LC 152Maximum Product SubarrayMedium
Stuck? Peek at the approach

Track both maximum and minimum products because negative values exchange their roles, and handle resets at zero.

Key points

  1. Define the state as "ending at i"; a contiguous subarray then has two transitions: extend the previous run or restart at i.
  2. A negative factor turns the maximum into the minimum, so keep both a max state and a min state.
  3. State-machine DP gives each position a few states (holding or not, previous taken or not) and writes out every transition between them.

Common pitfalls

  • Updating hi first and then computing lo from the new hi mixes values from the same step.
  • Starting the answer at 0 is wrong for an all-negative array.
  • Kadane's maximum subarray sum uses cur = max(x, cur + x); don't drop the restart option.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

State machine DP · stocks with a cooldown

Prices 1, 2, 3, 0, 2, with a one-day cooldown after selling: what is the best profit?

Try your own input
price
1day 0
2day 1
3day 2
0day 3
2day 4
hold
·hold[0]
·hold[1]
·hold[2]
·hold[3]
·hold[4]
cool
·cool[0]
·cool[1]
·cool[2]
·cool[3]
·cool[4]
free
·free[0]
·free[1]
·free[2]
·free[3]
·free[4]
CurrentDiscovered / computedAnswer
Day
—
Best profit
0

Each day ends in one of three states: holding a share, just sold (cooling down, no buying tomorrow), or free to buy. Each column comes from the previous one only.

InvariantEach day’s three states come only from the previous day’s: hold → cool (sell), free → hold (buy), cool → free (wait a day).

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 152, with it.

Python
def max_product(nums: list[int]) -> int:
    """Largest product of a non-empty contiguous subarray."""
    hi = lo = best = nums[0]  # max and min product of a subarray ending here
    for x in nums[1:]:
        cand = (x, hi * x, lo * x)  # restart, or extend; a negative x swaps max and min
        hi, lo = max(cand), min(cand)
        best = max(best, hi)
    return best
C++
// Largest product of a non-empty contiguous subarray.
long long maxProduct(const vector<int>& nums) {
    long long hi = nums[0], lo = nums[0], best = nums[0];  // max and min product ending here
    for (size_t i = 1; i < nums.size(); i++) {
        long long x = nums[i];
        long long a = hi * x, b = lo * x;  // a negative x swaps max and min
        hi = max({x, a, b});  // restart, or extend
        lo = min({x, a, b});
        best = max(best, hi);
    }
    return best;
}
Java
class Solution {
    // Largest product of a non-empty contiguous subarray.
    long maxProduct(int[] nums) {
        long hi = nums[0], lo = nums[0], best = nums[0]; // max and min product ending here
        for (int i = 1; i < nums.length; i++) {
            long x = nums[i], a = hi * x, b = lo * x; // a negative x swaps max and min
            hi = Math.max(x, Math.max(a, b)); // restart, or extend
            lo = Math.min(x, Math.min(a, b));
            best = Math.max(best, hi);
        }
        return best;
    }
}
Go
// maxProduct returns the largest product of a non-empty contiguous subarray.
func maxProduct(nums []int) int {
	hi, lo, best := nums[0], nums[0], nums[0] // max and min product ending here
	for _, x := range nums[1:] {
		a, b := hi*x, lo*x                  // a negative x swaps max and min
		hi, lo = max(x, a, b), min(x, a, b) // restart, or extend
		best = max(best, hi)
	}
	return best
}

Common variants

Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Circular subarray: total minus the smallest subarrayO(n) time · O(1) space

When the array wraps around, the best subarray either stays inside (plain Kadane) or wraps; a wrapping one is the total minus a middle part, so take the smallest subarray sum for that part. With all numbers negative, total minus smallest is the empty array, so fall back to plain Kadane. LC 918 (Maximum Sum Circular Subarray).

Python
def max_circular_subarray(nums: list[int]) -> int:
    """Largest sum of a non-empty subarray when the array wraps around (LC 918)."""
    best_max = cur_max = best_min = cur_min = total = nums[0]
    for x in nums[1:]:
        cur_max = max(x, cur_max + x)  # Kadane for the largest subarray...
        best_max = max(best_max, cur_max)
        cur_min = min(x, cur_min + x)  # ...and for the smallest
        best_min = min(best_min, cur_min)
        total += x
    # Wrapping = everything but a middle part. All negative: that would be empty, so don't.
    return max(best_max, total - best_min) if best_max > 0 else best_max
C++
// Largest sum of a non-empty subarray when the array wraps around (LC 918).
int maxCircularSubarray(const vector<int>& nums) {
    int bestMax = nums[0], curMax = nums[0], bestMin = nums[0], curMin = nums[0], total = nums[0];
    for (size_t i = 1; i < nums.size(); i++) {
        int x = nums[i];
        curMax = max(x, curMax + x);  // Kadane for the largest subarray...
        bestMax = max(bestMax, curMax);
        curMin = min(x, curMin + x);  // ...and for the smallest
        bestMin = min(bestMin, curMin);
        total += x;
    }
    // Wrapping = everything but a middle part. All negative: that would be empty, so don't.
    return bestMax > 0 ? max(bestMax, total - bestMin) : bestMax;
}
Java
class Solution {
    // Largest sum of a non-empty subarray when the array wraps around (LC 918).
    int maxCircularSubarray(int[] nums) {
        int bestMax = nums[0], curMax = nums[0], bestMin = nums[0], curMin = nums[0], total = nums[0];
        for (int i = 1; i < nums.length; i++) {
            int x = nums[i];
            curMax = Math.max(x, curMax + x); // Kadane for the largest subarray...
            bestMax = Math.max(bestMax, curMax);
            curMin = Math.min(x, curMin + x); // ...and for the smallest
            bestMin = Math.min(bestMin, curMin);
            total += x;
        }
        // Wrapping = everything but a middle part. All negative: that would be empty, so don't.
        return bestMax > 0 ? Math.max(bestMax, total - bestMin) : bestMax;
    }
}
Go
// maxCircularSubarray returns the largest sum of a non-empty subarray when the array wraps (LC 918).
func maxCircularSubarray(nums []int) int {
	bestMax, curMax, bestMin, curMin, total := nums[0], nums[0], nums[0], nums[0], nums[0]
	for _, x := range nums[1:] {
		curMax = max(x, curMax+x) // Kadane for the largest subarray...
		bestMax = max(bestMax, curMax)
		curMin = min(x, curMin+x) // ...and for the smallest
		bestMin = min(bestMin, curMin)
		total += x
	}
	// Wrapping = everything but a middle part. All negative: that would be empty, so don't.
	if bestMax > 0 {
		return max(bestMax, total-bestMin)
	}
	return bestMax
}
Two states: nothing deleted yet / one deletedO(n) time · O(1) space

For subarray problems that allow one deletion, flip or skip, add a dimension to the state ending at i: keep has the chance unused, dropped has used it. dropped either deletes x itself (taking the old keep) or deleted earlier and now extends with x. LC 1186 (Maximum Subarray Sum with One Deletion); LC 1911 and LC 926 also pass between two or three states.

Python
def max_sum_one_deletion(arr: list[int]) -> int:
    """Largest sum of a non-empty subarray with at most one element deleted (LC 1186)."""
    keep = best = arr[0]  # keep: best sum ending here with nothing deleted
    dropped = float("-inf")  # best sum ending here with one element deleted
    for x in arr[1:]:
        dropped = max(keep, dropped + x)  # delete x (old keep), or extend an earlier deletion
        keep = max(x, keep + x)
        best = max(best, keep, dropped)
    return best
C++
// Largest sum of a non-empty subarray with at most one element deleted (LC 1186).
long long maxSumOneDeletion(const vector<int>& arr) {
    long long keep = arr[0], best = arr[0];  // keep: best sum ending here with nothing deleted
    long long dropped = LLONG_MIN / 2;  // best sum ending here with one element deleted
    for (size_t i = 1; i < arr.size(); i++) {
        long long x = arr[i];
        dropped = max(keep, dropped + x);  // delete x (old keep), or extend an earlier deletion
        keep = max(x, keep + x);
        best = max({best, keep, dropped});
    }
    return best;
}
Java
class Solution {
    // Largest sum of a non-empty subarray with at most one element deleted (LC 1186).
    long maxSumOneDeletion(int[] arr) {
        long keep = arr[0], best = arr[0]; // keep: best sum ending here with nothing deleted
        long dropped = Long.MIN_VALUE / 2; // best sum ending here with one element deleted
        for (int i = 1; i < arr.length; i++) {
            long x = arr[i];
            dropped = Math.max(keep, dropped + x); // delete x (old keep), or extend an earlier deletion
            keep = Math.max(x, keep + x);
            best = Math.max(best, Math.max(keep, dropped));
        }
        return best;
    }
}
Go
// maxSumOneDeletion returns the largest subarray sum with at most one element deleted (LC 1186).
func maxSumOneDeletion(arr []int) int {
	keep, best := arr[0], arr[0] // keep: best sum ending here with nothing deleted
	dropped := -1 << 60 // best sum ending here with one element deleted
	for _, x := range arr[1:] {
		dropped = max(keep, dropped+x) // delete x (old keep), or extend an earlier deletion
		keep = max(x, keep+x)
		best = max(best, keep, dropped)
	}
	return best
}

Why it works

  1. A contiguous subarray ending at i is either nums[i] alone or a subarray ending at i − 1 extended by nums[i], so restart and extend cover every case.
  2. Multiplying by a negative number swaps the largest and the smallest, so the best product ending at i must be one of x, hi·x and lo·x; tracking both hi and lo makes the case analysis complete.
  3. The answer is the maximum of hi over all positions, not the last hi, because the best subarray can end anywhere.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
连续子数组的题,我把状态定义成以 i 结尾,这样只有两种转移:接在前一个后面,或者从 i 重新开始。最大乘积子数组里,负数会让最大值和最小值互换,所以我同时维护以 i 结尾的最大乘积和最小乘积,新值从 x、hi 乘 x、lo 乘 x 三个候选里取。答案是每个位置 hi 的最大值。一遍扫描,O(n) 时间、O(1) 空间。
English
For contiguous subarray problems I define the state as ending at i, which leaves two transitions: extend the previous run or restart at i. In maximum product subarray a negative number swaps the largest and smallest products, so I keep both the max and the min ending at i, and each new value comes from x, hi times x or lo times x. The answer is the largest hi seen at any position. It is one pass, O(n) time and O(1) space.

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

3 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

3 questions
  1. House Robber on a circle (first and last houses are neighbours) is usually solved how?
  2. Stock trading with a one-day cooldown uses states hold, sold (sold today) and rest (not holding, no cooldown). Buying today comes from which state yesterday?
  3. Stock trading with a fee: each day hold = max(hold, cash - p); cash = max(cash, hold + p - fee), where the second line sees the updated hold. Why is updating in place safe?

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

Practice by stage

This stop's 6 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Core 5

#ProblemApproachRating
152Maximum Product SubarrayTrack both maximum and minimum products because negative values exchange their roles, and handle resets at zero.
918Maximum Sum Circular SubarrayExpress a maximum sum crossing the array boundary as total sum minus the minimum subarray, handling all-negative input separately.Rating 1777
1911Maximum Alternating Subsequence SumTrack addition and subtraction states by the parity of the number of selected elements, not by original array indices.Rating 1786
926Flip String to Monotone IncreasingSeparate monotonic binary strings into the all-zero phase and the phase that has entered ones, comparing prefix-count solutions.Rating 1602
1653Minimum Deletions to Make String BalancedPreserve character order by choosing between deleting the current a and deleting earlier b characters, practicing linear state compression.Rating 1794

Advanced 1

#ProblemApproachRating
1186Maximum Subarray Sum with One DeletionRepresent the one-time deletion with unused and used states, ensuring the resulting subarray remains nonempty.Rating 1799