BackhardHeapGoldman SachsAmazon

Heavy-Light Path Sum Resolver 2 Solution

Problem Statement

You are tasked with processing a sequence of $N$ integer weights representing nodes in a linear dependency chain. The objective is to compute the 'Heavy-Light Path Sum' by maintaining a dynamic window of the most significant elements using a Min-Max Priority Heap Queue strategy. Specifically, you must identify the maximum sum of any contiguous subsequence of length $K$ within the array, but with a twist: at each step, you must efficiently track the top $K$ largest values and the bottom $K$ smallest values to resolve conflicts in overlapping windows.

Given an array nums of length $N$ and an integer $K$, return the maximum possible sum of any subarray of length $K$. To solve this efficiently for large $N$, you are expected to utilize a dual-heap structure (a min-heap for the lower bound and a max-heap for the upper bound) to maintain the active window's aggregate properties in $O(\log K)$ time per operation. The 'Heavy-Light' terminology refers to the balancing of high-value (heavy) and low-value (light) elements within the sliding window to ensure optimal sum calculation without recalculating the entire window sum from scratch for every shift.

Input: An integer array nums and an integer K. Output: An integer representing the maximum sum of any contiguous subarray of length $K$.

Example 1
Input
nums = [1, 2, 3, 4, 5], K = 3
Output
12

Explanation: The contiguous subarrays of length 3 are: [1,2,3] (sum=6), [2,3,4] (sum=9), [3,4,5] (sum=12). The maximum sum is 12.

Example 2
Input
nums = [5, 4, 3, 2, 1], K = 2
Output
9

Explanation: The contiguous subarrays of length 2 are: [5,4] (sum=9), [4,3] (sum=7), [3,2] (sum=5), [2,1] (sum=3). The maximum sum is 9.

Example 3
Input
nums = [-1, -2, -3, -4], K = 2
Output
-3

Explanation: The contiguous subarrays of length 2 are: [-1,-2] (sum=-3), [-2,-3] (sum=-5), [-3,-4] (sum=-7). The maximum sum is -3.

Example 4
Input
nums = [10, 1, 1, 1, 10], K = 3
Output
12

Explanation: The contiguous subarrays of length 3 are: [10,1,1] (sum=12), [1,1,1] (sum=3), [1,1,10] (sum=12). The maximum sum is 12.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= K <= nums.length
  • -10^9 <= nums[i] <= 10^9
  • The answer is guaranteed to fit in a 64-bit integer.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Heavy-Light Path Sum Resolver 2 — Problem Statement & Solution Guide

HeapHardMin-Max Priority Heap Queue
TimeO(N)
|
SpaceO(1)

Problem Description

You are tasked with processing a sequence of $N$ integer weights representing nodes in a linear dependency chain. The objective is to compute the 'Heavy-Light Path Sum' by maintaining a dynamic window of the most significant elements using a Min-Max Priority Heap Queue strategy. Specifically, you must identify the maximum sum of any contiguous subsequence of length $K$ within the array, but with a twist: at each step, you must efficiently track the top $K$ largest values and the bottom $K$ smallest values to resolve conflicts in overlapping windows.

Given an array nums of length $N$ and an integer $K$, return the maximum possible sum of any subarray of length $K$. To solve this efficiently for large $N$, you are expected to utilize a dual-heap structure (a min-heap for the lower bound and a max-heap for the upper bound) to maintain the active window's aggregate properties in $O(\log K)$ time per operation. The 'Heavy-Light' terminology refers to the balancing of high-value (heavy) and low-value (light) elements within the sliding window to ensure optimal sum calculation without recalculating the entire window sum from scratch for every shift.

Input: An integer array nums and an integer K.

Output: An integer representing the maximum sum of any contiguous subarray of length $K$.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Heavy-Light Path Sum Resolver 2"

hard

WHY DOES IT MATTER?

The sliding‑window pattern transforms a seemingly quadratic problem into linear time by reusing overlapping computation, a technique that appears in many real‑world streaming and time‑series analyses where you must continuously evaluate a metric over a moving interval.

OPTIMIZATION CHALLENGE

The key insight is that adjacent windows differ by exactly two elements—one exiting and one entering—so the sum can be updated in constant time. Recognizing this overlap eliminates the need for nested loops or expensive data structures.

REAL-WORLD CONNECTION

Think of a network router that monitors the total bytes transferred over the last 5 seconds. As each packet arrives, the router subtracts the bytes that fell out of the 5‑second window and adds the new packet size, keeping a running total without rescanning the entire history.

During an interview, write the initial O(N·K) version quickly to show you understand the brute force, then immediately point out the overlapping nature of windows and transition to the O(N) sliding‑window solution; this demonstrates both correctness and performance awareness.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(1)

Core Theory — Why This Approach?

The Heavy‑Light Path Sum problem asks for the maximum sum of any contiguous sub‑array of fixed length K. A naïve solution would recompute the sum for every possible window, leading to O(N·K) time, which quickly becomes infeasible for N up to 10^6 or larger. The optimal paradigm leverages the sliding‑window technique: as the window moves one position to the right, we subtract the element that leaves the window and add the new element that enters, updating the current sum in O(1) time. This yields an overall O(N) linear scan. Some interviewers like to see a Min‑Max Priority Heap (also called a double‑ended priority queue) to illustrate how one could maintain the window’s elements while supporting O(log K) removal of the outgoing element and O(log K) insertion of the incoming element, but the heap is unnecessary for pure sum computation. Understanding why the sliding‑window works—because the sum of a window can be expressed incrementally—highlights the importance of reusing previously computed information rather than recomputing from scratch.

Interview Questions on This Problem

Q1How would you find the maximum sum of any sub‑array of length K in O(N) time?

Initialize the sum of the first K elements, store it as the current maximum, then slide the window: for each i from K to N‑1, update sum = sum + arr[i] – arr[i‑K] and keep the maximum seen so far. This runs in O(N) time and O(1) extra space.

Q2If the array contains both positive and negative numbers, does the sliding‑window approach still work for fixed‑size K?

Yes. The sliding‑window update does not depend on sign; it always adds the new element and removes the old one, preserving the exact sum of the current K‑length segment, so the algorithm remains correct for any integer values.

Q3When would a Min‑Max Heap be a justified alternative to the O(1) sliding‑window sum?

A Min‑Max Heap becomes useful if the problem asks for the maximum (or minimum) element inside each sliding window, or if we need to support arbitrary deletions and insertions while also querying the window’s extremal values. In that case each slide costs O(log K) instead of O(1), but it provides the extra functionality.

Examples

Example 1

Input

nums = [1, 2, 3, 4, 5], K = 3

Output

12

Explanation: The contiguous subarrays of length 3 are: [1,2,3] (sum=6), [2,3,4] (sum=9), [3,4,5] (sum=12). The maximum sum is 12.

Example 2

Input

nums = [5, 4, 3, 2, 1], K = 2

Output

9

Explanation: The contiguous subarrays of length 2 are: [5,4] (sum=9), [4,3] (sum=7), [3,2] (sum=5), [2,1] (sum=3). The maximum sum is 9.

Example 3

Input

nums = [-1, -2, -3, -4], K = 2

Output

-3

Explanation: The contiguous subarrays of length 2 are: [-1,-2] (sum=-3), [-2,-3] (sum=-5), [-3,-4] (sum=-7). The maximum sum is -3.

Example 4

Input

nums = [10, 1, 1, 1, 10], K = 3

Output

12

Explanation: The contiguous subarrays of length 3 are: [10,1,1] (sum=12), [1,1,1] (sum=3), [1,1,10] (sum=12). The maximum sum is 12.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= K <= nums.length
  • -10^9 <= nums[i] <= 10^9
  • The answer is guaranteed to fit in a 64-bit integer.

Optimal Approach & Strategy

Use a sliding window: maintain the current sum, update it by removing the leftmost element and adding the new rightmost element, achieving O(N) time and O(1) extra space.

Brute Force Approach

Compute the sum for every possible K‑length sub‑array by iterating K elements for each start index, resulting in O(N·K) time.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function solution(nums) {
   if (nums.length < 2) return 0;
   let minHeap = new MinHeap();
   let maxHeap = new MaxHeap();
   for (let num of nums) {
       minHeap.insert(num);
       maxHeap.insert(num);
   }
   let maxSum = 0;
   while (minHeap.size() > 0 && maxHeap.size() > 0) {
       let min = minHeap.extractMin();
       let max = maxHeap.extractMax();
       maxSum = Math.max(maxSum, min + max);
   }
   return maxSum;
}

Asked in Top Tech Interviews

Goldman SachsAmazon

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.