Smallest sum contiguous subarray

Pattern: Kadane and subarray sums

medium

Kadane's algorithm with min in place of max. Keep the smallest sum of a block ending here, and start a new block whenever the old one is positive.

The problem

Given an array of whole numbers, return the smallest sum of a non-empty block of neighbouring elements. For example, [3, -4, 2, -3, -1, 7, -5] gives -6 (-4 + 2 - 3 - 1), and [2, 6, 8, 1, 4] gives 1.

The link above is a GeeksforGeeks article on this problem. The function name smallestSumSubarray is this guide's own.

Think first

  • How does Maximum Subarray change if you want the smallest sum?
  • When is the old run worth keeping now?
  • What is the answer when every value is positive?

Hints

    Brute force, and why it fails

    Try every block with a running sum: O(n²). One Kadane pass is O(n). You can also negate every value, run Maximum Subarray, and negate the answer.

    The key insight

    The argument behind Kadane's algorithm does not care whether you want the largest or the smallest. Flip max to min and it still holds.

    Dry run

    30i
    -41 
    22 
    -33 
    -14 
    75 
    -56 
    current3
    best3

    arr = [3, -4, 2, -3, -1, 7, -5]. current is the smallest sum of a block ending here. Start at 3.

    Step 1 of 4

    The plan

    current = arr[0], best = arr[0]
    for i from 1 to n - 1:
        current = min(arr[i], current + arr[i])
        best = min(best, current)
    return best
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One pass with two numbers.

    Edge cases

    • All positive: the smallest single value.
    • All negative: the sum of the whole array.
    • One element: that element.
    I've built my logic, show the code

    Java

    class Solution {
        public int smallestSumSubarray(int[] arr) {
            int best = arr[0];
            int current = arr[0];                   // smallest sum of a subarray that ends here
            for (int i = 1; i < arr.length; i++) {
                current = Math.min(arr[i], current + arr[i]);   // extend the old run, or start again here
                best = Math.min(best, current);
            }
            return best;
        }
    }

    C++

    class Solution {
    public:
        int smallestSumSubarray(vector<int>& arr) {
            int best = arr[0];
            int current = arr[0];                   // smallest sum of a subarray that ends here
            for (int i = 1; i < static_cast<int>(arr.size()); i++) {
                current = min(arr[i], current + arr[i]);   // extend the old run, or start again here
                best = min(best, current);
            }
            return best;
        }
    };

    Python

    class Solution:
        def smallestSumSubarray(self, arr: list[int]) -> int:
            best = current = arr[0]                 # current: smallest sum of a subarray that ends here
            for v in arr[1:]:
                current = min(v, current + v)       # extend the old run, or start again here
                best = min(best, current)
            return best

    Common mistakes

    • Changing only one of the two max calls to min.
    • Starting best at 0, which returns 0 for an all-positive array.
    • Mixing up "smallest sum" with "shortest block".

    Similar problems