s LearnSqueak.com

SMALLTALK LAB

Maximum Subarray in Squeak: Kadane’s Running Decision

Find the best contiguous run in linear time, recover its endpoints, handle all-negative input, and cross-check the result with a brute-force oracle.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Use a fresh Workspace and Print it on each complete independent expression. Arrays must be nonempty and numeric. A subarray is contiguous and must contain at least one element in this lesson. The native visual replay shows a running sum and the best interval so far.

These are native Squeak 6.1 examples. Each checkpoint is independent: open the download as text, copy one complete expression into Workspace and choose Print it. Do not file in the checkpoint collection as a class definition.

Expected values are Smalltalk expressions. The printer may show explicit Symbol markers: #(A B) and #(#A #B) represent the same array of Symbols.

01 - Distinguish a contiguous run from a subsequence

Choose one uninterrupted slice. You cannot skip a loss inside the selected interval. In this example the best slice is #(4 -1 2 1), not the disconnected positive values. copyFrom:to: includes both one-based endpoints.

Independent Workspace expression - select all, then Print it
| values slice |
values := #(-2 1 -3 4 -1 2 1 -5 4).
slice := values copyFrom: 4 to: 7.
{slice. slice sum}

Expected: #(#(4 -1 2 1) 6)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Distinguish a contiguous run from a subsequence
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Compare the slice sum with the sum of all positive elements; that solves a different problem.

Download this checkpoint

02 - Decide whether to extend or restart

Let ending be the best sum of a nonempty subarray ending at the previous position. For the next value, either extend that subarray or start fresh. If ending is negative, carrying it forward can only hurt. This recurrence is local, but its best-so-far value will give a global answer.

Independent Workspace expression - select all, then Print it
| ending value |
ending := -4. value := 3.
{ending + value. value. ((ending + value) max: value)}

Expected: #(-1 3 3)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Decide whether to extend or restart
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: If ending is 5 and the next value is -2, extend to 3 rather than restart at -2.

Download this checkpoint

03 - Track endings separately from the best answer

The best sum ending here may go down. The best sum anywhere so far cannot go down. This checkpoint records both after every input element. Initialization from the first value enforces the nonempty requirement.

Independent Workspace expression - select all, then Print it
| values ending best endings bests |
values := #(-2 1 -3 4 -1 2 1 -5 4).
ending := values first. best := ending.
endings := OrderedCollection with: ending.
bests := OrderedCollection with: best.
2 to: values size do: [:i |
 ending := (values at: i) max: (ending + (values at: i)).
 best := best max: ending.
 endings add: ending. bests add: best].
{endings asArray. bests asArray}

Expected: #(#(-2 1 -2 4 3 5 6 1 5) #(-2 1 1 4 4 5 6 6 6))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Track endings separately from the best answer
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: At position 8 the ending sum falls to 1, but the saved best remains 6.

Download this checkpoint

04 - Save endpoints only when the best improves

start belongs to the currently active candidate. bestStart and bestEnd belong to the saved answer. Update the saved endpoints only on a strict improvement. With this tie policy, zero-sum prefixes are retained and an already saved equal best is not replaced.

Independent Workspace expression - select all, then Print it
| values ending best start bestStart bestEnd |
values := #(-2 1 -3 4 -1 2 1 -5 4).
ending := values first. best := ending.
start := 1. bestStart := 1. bestEnd := 1.
2 to: values size do: [:i | | value |
 value := values at: i.
 ending < 0
  ifTrue: [ending := value. start := i]
  ifFalse: [ending := ending + value].
 ending > best ifTrue: [
  best := ending. bestStart := start. bestEnd := i]].
{best. bestStart. bestEnd. values copyFrom: bestStart to: bestEnd}

Expected: #(6 4 7 #(4 -1 2 1))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Save endpoints only when the best improves
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: The interval is inclusive; its length is bestEnd - bestStart + 1.

Download this checkpoint

05 - Keep an all-negative answer nonempty

Initializing best to zero would silently allow the empty subarray and produce a wrong answer for this contract. Starting from the first element finds the least-negative value instead. A one-element array follows the same logic with no loop iterations.

Independent Workspace expression - select all, then Print it
| values ending best start bestStart bestEnd |
values := #(-8 -3 -6 -2 -5 -4).
ending := values first. best := ending.
start := 1. bestStart := 1. bestEnd := 1.
2 to: values size do: [:i | | value |
 value := values at: i.
 ending < 0
  ifTrue: [ending := value. start := i]
  ifFalse: [ending := ending + value].
 ending > best ifTrue: [
  best := ending. bestStart := start. bestEnd := i]].
{best. bestStart. bestEnd}

Expected: #(-2 4 4)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Keep an all-negative answer nonempty
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Try #(-7), then #(0). Their answers are -7 and 0, both with endpoints 1 and 1.

Download this checkpoint

06 - Make ties deliberate and predictable

Restart only when ending is strictly negative, and save only when ending is strictly greater than best. This keeps the earliest ending among equal best sums; for that ending it retains the earliest start produced by keeping zero-sum prefixes. Different valid policies can return a different interval with the same maximum sum.

Independent Workspace expression - select all, then Print it
| values ending best start bestStart bestEnd |
values := #(0 2 -2 2).
ending := values first. best := ending.
start := 1. bestStart := 1. bestEnd := 1.
2 to: values size do: [:i | | value |
 value := values at: i.
 ending < 0
  ifTrue: [ending := value. start := i]
  ifFalse: [ending := ending + value].
 ending > best ifTrue: [
  best := ending. bestStart := start. bestEnd := i]].
{best. bestStart. bestEnd}

Expected: #(2 1 2)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Make ties deliberate and predictable
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Changing ending < 0 to ending <= 0 drops zero-sum prefixes and favors shorter starts. Changing > to >= changes which equal best ending is retained.

Download this checkpoint

07 - Build a small independent oracle

For short inputs, enumerate all contiguous intervals. Extend a running sum for each start rather than recomputing each slice. This O(n squared) oracle follows a different route from Kadane and makes an effective test. Keep it small; it is not the production algorithm.

Independent Workspace expression - select all, then Print it
| values oracle |
values := #(-2 1 -3 4 -1 2 1 -5 4).
oracle := values first.
1 to: values size do: [:left | | sum |
 sum := 0.
 left to: values size do: [:right |
  sum := sum + (values at: right).
  oracle := oracle max: sum]].
oracle

Expected: 6

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: Build a small independent oracle
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: The oracle checks the maximum sum. Endpoint tie policies need separate tests.

Download this checkpoint

08 - Cross-check several boundary cases

Package each implementation as a block, then compare them on short varied arrays. Test all-negative, singleton, zero, ties, and a maximum at the final element. The linear algorithm uses O(n) arithmetic operations and O(1) auxiliary storage when it does not save trace arrays.

Independent Workspace expression - select all, then Print it
| fast slow cases |
fast := [:values | | ending best |
 ending := values first. best := ending.
 2 to: values size do: [:i |
  ending := (values at: i) max: (ending + (values at: i)).
  best := best max: ending]. best].
slow := [:values | | best |
 best := values first.
 1 to: values size do: [:left | | sum |
  sum := 0.
  left to: values size do: [:right |
   sum := sum + (values at: right).
   best := best max: sum]]. best].
cases := #((-8 -3 -6) (9) (0) (0 2 -2 2) (-4 1 2 3)).
{(cases collect: [:values | fast value: values]).
 (cases allSatisfy: [:values | (fast value: values) = (slow value: values)])}

Expected: #(#(-3 9 0 2 6) true)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Cross-check several boundary cases
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Add #(-1 5 -1 5 -20) and expect 9. Reject empty input before calling either block.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
Maximum Subarray in Squeak: Kadane’s Running Decision native visual trace
Replay of actual Morphic window captures at successive computed stages; not mouse footage.

Download the visual experiment. Select the entire expression and Do it. Change stage := 0. to another supported stage, close the previous window, and run again. The GIF replays those native states. This example needs native Squeak; no new browser playground compatibility is claimed.

Reason about correctness and limits

A subarray is contiguous; a subsequence may skip values. Selecting all positive elements is not Kadane’s problem.

The empty array has no nonempty subarray. These expressions require a nonempty array; a reusable method should reject emptiness or return an explicit absence result.

Do not initialize a nonempty maximum to zero. That fails on all-negative data.

The active candidate start is not necessarily the saved answer start. Keep separate endpoint variables.

Ties are not errors: several intervals can have the same maximum sum. Document the restart and replacement rules.

Integer examples are exact. Floating-point inputs introduce rounding, and NaN or infinities need a separately specified contract.

The linear running algorithm needs constant auxiliary space. The trace checkpoint deliberately stores O(n) states for teaching; the verification oracle deliberately takes O(n squared) time.

Three practice challenges

Maximum at the end

Find the sum and endpoints for #(-5 2 -1 4).

Show solution

The maximum is 5 for positions 2 through 4: #(2 -1 4). The final position improves the best answer.

Allow the empty interval

How would the result contract change if an empty subarray were allowed?

Show solution

Its sum is zero, so all-negative inputs would return zero and an explicit empty interval. Initialize running and best sums to zero and clamp the running sum to zero, but define an unambiguous endpoint representation for emptiness.

Minimum subarray

Adapt the recurrence to find a nonempty minimum-sum interval.

Show solution

Replace max: with min:, restart when the previous ending sum is positive, and save a strict smaller best. Initialize from the first element to preserve nonempty semantics.

Continue learning

Sliding Window | Prefix Sums | Collections

Environment reference: official Squeak documentation. This lesson and its examples are original. Verified using native Squeak 6.1 build 23976 on Linux.