BackmediumQueueAccentureMicrosoft

Sequential Node Cluster Solution

Problem Statement

You are given an integer array nums. A sequential node cluster is a contiguous sub‑array in which the absolute difference between every pair of consecutive elements does not exceed 1; formally, for a sub‑array nums[l…r] it must hold that |nums[i]‑nums[i‑1]| ≤ 1 for all i with l < i ≤ r. Your task is to compute the maximum possible sum of any sequential node cluster in nums and return that sum.

Input: The first line contains an integer n, the length of the array. The second line contains n space‑separated integers representing nums. Output: A single integer – the largest sum among all valid clusters.

If the array contains only one element, the answer is that element itself, because a single element trivially satisfies the cluster condition.

Example 1
Input
8 4 5 5 6 2 3 4 5
Output
20

Explanation: The array can be split into two clusters: [4,5,5,6] (differences 1,0,1) with sum 20, and [2,3,4,5] (differences 1,1,1) with sum 14. The maximum sum is 20.

Example 2
Input
9 1 2 4 5 6 5 4 3 2
Output
29

Explanation: The first two numbers form a cluster [1,2] (sum 3). Starting from index 2 we obtain a longer cluster [4,5,6,5,4,3,2] where each adjacent difference is 1. Its sum is 4+5+6+5+4+3+2 = 29, which is the largest possible.

Example 3
Input
5 10 9 8 7 6
Output
40

Explanation: All consecutive differences are exactly 1, so the whole array is a single cluster. The sum is 10+9+8+7+6 = 40.

Constraints

  • 1 <= nums.length <= 100000
  • -10^9 <= nums[i] <= 10^9
  • The algorithm should run in O(n) time and O(1) additional space.
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

Sequential Node Cluster — Problem Statement & Solution Guide

QueueMediumTask Scheduling
TimeO(n)
|
SpaceO(1)

Problem Description

You are given an integer array nums. A *sequential node cluster* is a contiguous sub‑array in which the absolute difference between every pair of consecutive elements does not exceed 1; formally, for a sub‑array nums[l…r] it must hold that |nums[i]‑nums[i‑1]| ≤ 1 for all i with l < i ≤ r. Your task is to compute the maximum possible sum of any sequential node cluster in nums and return that sum.

Input: The first line contains an integer n, the length of the array. The second line contains n space‑separated integers representing nums.

Output: A single integer – the largest sum among all valid clusters.

If the array contains only one element, the answer is that element itself, because a single element trivially satisfies the cluster condition.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Sequential Node Cluster"

medium

WHY DOES IT MATTER?

The sliding‑window pattern efficiently solves problems where a global optimum depends on a local, contiguous condition. Recognizing that the constraint is *monotonic* (once broken it never recovers without resetting) lets us avoid recomputation and achieve linear performance, a skill that differentiates senior‑level candidates.

OPTIMIZATION CHALLENGE

The key insight is that the window can be extended greedily until the |Δ|≤1 rule fails; at that point the left pointer jumps to the current element, resetting the sum. This eliminates the need for nested loops or prefix‑sum recomputation.

REAL-WORLD CONNECTION

Think of a network packet stream where packets must arrive within a bounded jitter (difference in timestamps). Detecting the longest high‑throughput burst that respects jitter limits mirrors finding the maximum‑sum sequential node cluster.

During an interview, write the two‑pointer loop first, then add the running sum update inside the same block. Keep the code tight: one if‑else to either extend the window or reset it, and update the answer after each iteration.

COMPLEXITY AT A GLANCE

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

Core Theory — Why This Approach?

The problem asks for the maximum sum of a contiguous sub‑array where the absolute difference between any two consecutive elements is at most 1. This constraint creates a *monotone* region: once an element violates the |Δ|≤1 rule, the current cluster must end. A naïve solution would enumerate every possible sub‑array, check the constraint, and compute its sum, leading to O(n²) time – infeasible for n up to 10⁵ or higher. The optimal paradigm treats the array as a stream and maintains a sliding window that expands while the constraint holds and contracts the moment it breaks. By keeping a running sum of the window, we can update the candidate answer in O(1) per element, achieving overall linear time. This approach is a classic example of a two‑pointer / sliding‑window technique combined with incremental aggregation, which is optimal for any problem that requires the best sub‑segment under a local adjacency condition.

Interview Questions on This Problem

Q1How would you modify the solution if the allowed difference between consecutive elements was a variable k instead of a fixed 1?

Replace the constant check |nums[i]‑nums[i‑1]| ≤ 1 with |nums[i]‑nums[i‑1]| ≤ k. The sliding‑window logic stays identical; only the condition changes, so the algorithm remains O(n) time and O(1) space.

Q2Can you compute the maximum sum of a sequential node cluster in a circular array (i.e., the array wraps around)?

Duplicate the array (concatenate it to itself) and run the linear sliding‑window on the doubled array, but limit the window length to at most the original array size n. This preserves O(n) time while handling wrap‑around clusters.

Q3What is the relationship between this problem and the classic "Maximum Subarray Sum" (Kadane’s algorithm), and why can Kadane’s not be applied directly?

Kadane’s algorithm maximizes sum without any adjacency constraints, while here we must enforce |Δ|≤1 for every adjacent pair. Kadane’s may include elements that break the constraint, so we need a sliding window that respects the local difference rule before aggregating sums.

Examples

Example 1

Input

8
4 5 5 6 2 3 4 5

Output

20

Explanation: The array can be split into two clusters: [4,5,5,6] (differences 1,0,1) with sum 20, and [2,3,4,5] (differences 1,1,1) with sum 14. The maximum sum is 20.

Example 2

Input

9
1 2 4 5 6 5 4 3 2

Output

29

Explanation: The first two numbers form a cluster [1,2] (sum 3). Starting from index 2 we obtain a longer cluster [4,5,6,5,4,3,2] where each adjacent difference is 1. Its sum is 4+5+6+5+4+3+2 = 29, which is the largest possible.

Example 3

Input

5
10 9 8 7 6

Output

40

Explanation: All consecutive differences are exactly 1, so the whole array is a single cluster. The sum is 10+9+8+7+6 = 40.

Constraints

  • 1 <= nums.length <= 100000
  • -10^9 <= nums[i] <= 10^9
  • The algorithm should run in O(n) time and O(1) additional space.

Optimal Approach & Strategy

Use two pointers to maintain a sliding window that satisfies the adjacency constraint, updating a running sum as the window expands or resets. Track the maximum sum encountered, achieving O(n) time and O(1) space.

Brute Force Approach

Enumerate every possible sub‑array, verify the |Δ|≤1 condition for each, and compute its sum; keep the maximum. This requires O(n²) time and O(1) extra space.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function solution(nums) {
   let cluster = [nums[0]];
   let sum = nums[0];
   for (let i = 1; i < nums.length; i++) {
       if (Math.abs(nums[i] - nums[i - 1]) <= 1) {
           cluster.push(nums[i]);
           sum += nums[i];
       }
   }
   return sum;
}

Asked in Top Tech Interviews

AccentureMicrosoft

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.