Problem 689

Abstract / Summary

Find the highest total of three separate groups of consecutive numbers in a list without their ranges touching.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0689.py

class Solution:
    def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]:
        size = len(nums)

        # prefix sum
        prefix = [ 0 ]
        for n in nums:
            prefix.append(prefix[-1] + n)

        # sum of the k-sized subarray starting here
        here  = [ b - a for a, b in zip(prefix, prefix[k :]) ]

        # maximum sum and its location, scanning from the left side
        left = []
        best = 0
        pos  = 0
        for i in range(len(here)):
            if  best < here[i]:
                best = here[i]
                pos = i

            left.append(( best, pos ))

        # and from the right side
        right = deque()
        best  = 0
        pos   = 0
        for i in reversed(range(len(here))):
            if  best <= here[i]: # small difference: always pick the smaller position if equal
                best  = here[i]
                pos   = i

            right.appendleft(( best, pos ))

        best   = 0
        result = []
        for i in range(k, len(right) - k):
            one, pos1 = left [i - k]
            two, pos2 = right[i + k]
            have = one + here[i] + two
            if  best < have:
                best = have
                result = ( pos1, i, pos2 )

        return result
45 lines | 1328 bytes | submitted July 10, 2024 | GitHub   15% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
  • Prefix Sum
  • Sliding Window
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The maxSumOfThreeSubarrays method receives an integer list nums and a window size k. It returns the starting indices of three non-overlapping subarrays of length k whose total sum is maximal. The algorithm proceeds in four logical phases: building a prefix-sum array, converting it to a list of all possible k-length window sums, scanning from the left to record the best window seen so far, scanning from the right to record the best window for every suffix, and finally evaluating every feasible middle window while combining the pre-computed left and right information.

Prefix Sum Construction

A classic prefix-sum array is created so that any range sum can be obtained in constant time. The first element is zero, and each subsequent entry accumulates the running total of nums.

prefix = [0]
for n in nums:
    prefix.append(prefix[-1] + n)

Subarray Sum Computation

Using the prefix array, the sum of each contiguous block of length k is computed by subtracting the prefix value at the start of the block from the prefix value just after the block. The resulting list here holds the sum for every possible window, indexed by its starting position.

here = [b - a for a, b in zip(prefix, prefix[k:])]

Left-to-Right Scan for Best Prefix

While iterating over here, the algorithm maintains the maximum window sum encountered so far (best) and the position where it occurs (pos). For each index it stores a tuple containing the current best sum and its location. This produces the left list, where left[i] represents the optimal window among all windows that end at or before index i.

left = []
best = 0
pos = 0
for i in range(len(here)):
    if best < here[i]:
        best = here[i]
        pos = i
    left.append((best, pos))

Right-to-Left Scan for Best Suffix

Scanning from the end of here yields analogous information for suffixes. A deque is used so that elements can be efficiently added to the front, preserving order for later indexing. The condition best <= here[i] ensures that when two windows have equal sum, the one with the smaller starting index (i.e., the later one in the original array) is preferred, which aligns with the problem’s tie-breaking rule.

right = deque()
best = 0
pos = 0
for i in reversed(range(len(here))):
    if best <= here[i]:
        best = here[i]
        pos = i
    right.appendleft((best, pos))

Combining Three Subarrays

The final phase iterates over every possible middle window, constrained to start at least k positions after the beginning and end at least k positions before the array’s end. For each middle index i, the algorithm retrieves the best left window that ends before i (left[i - k]) and the best right window that starts after i (right[i + k]). The total of the three windows is compared against the current global best, and the corresponding triple of positions is stored when a larger total is found.

best = 0
result = []
for i in range(k, len(right) - k):
    one, pos1 = left[i - k]
    two, pos2 = right[i + k]
    have = one + here[i] + two
    if best < have:
        best = have
        result = (pos1, i, pos2)

The method finally returns result, a tuple of the three starting indices.

Edge Cases Handled

When multiple windows share the same sum, the left scan keeps the earliest occurrence because it updates only on a strictly greater sum. Conversely, the right scan prefers the later occurrence due to the <= comparison, satisfying the requirement that the smallest lexicographic index triple be chosen. The loops that build left and right naturally handle the situation where k equals the length of nums divided by three, because the range limits in the final combination loop (range(k, len(right) - k)) guarantee that the three windows never overlap. The prefix-sum construction also gracefully deals with an empty input list, producing an empty here and consequently an empty result without raising an exception.

Performance Optimizations

The algorithm avoids recomputing window sums by leveraging the prefix-sum array, turning each k-length sum into a constant-time subtraction. The left and right scans each traverse the here list exactly once, storing only the best sum and its position, which eliminates the need for nested loops. The use of a deque for the right-side information enables O(1) insertion at the front while preserving direct index access, allowing the final combination loop to retrieve left and right candidates in constant time per iteration. Overall, the solution achieves linear work relative to the length of nums, with only a few auxiliary arrays of the same size, ensuring efficient use of both time and memory.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long row of numbered toy blocks. The goal of this puzzle is to pick three separate groups of blocks. Each group must be exactly three blocks wide, like a little train, and you want to pick them so that the total number of dots on all the blocks is as big as possible.

First, the code makes a list that keeps a running total of the dots as it walks down the row. This makes it really fast to figure out how many dots are in any small group.

Next, it creates a list that remembers the best group it has seen so far if it walks from the beginning to the end. It records two things: the high number of dots found and exactly where that group starts. It does the same thing again by walking backward from the end to the beginning to find the best group from the other side.

Finally, it puts everything together. It picks a group in the middle and looks at the best group it already found to the left and the best group it found to the right. It adds the dots from all three spots to see if, together, they make the biggest pile of dots possible. It keeps track of the middle group it is looking at and updates its favorite total until it finds the winning spots for all three groups of blocks.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.44 | σ = 1.17

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Go Python TS
LeetcodeHelp C++ Java Python
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fengvyi C++
JoshCrozier JS
MacJim C++
ruoru Rust
Shamik07 Dart
suxrobGM C#
vli02 C
wisdompeak C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fengvyi C++
JoshCrozier JavaScript
MacJim C++
ruoru Rust
Shamik07 Dart
suxrobGM C#
vli02 C
wisdompeak C++
zfang399 C++
32 links | 18 authors | 10 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

3 solutions   July 10, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality