BackmediumArraysAmazon

Maximum Equal-Endpoint Subarray Sum Solution

Problem Statement

Given an array of integers nums and an integer k, find the maximum sum of a contiguous subarray of length at least k such that the first and last elements of the subarray are equal.

Example 1
Input
[4, -1, 2, 4, -1, 2, 4, -1, 2, 4]
Output
12

Explanation: Step-by-step: Given the input array [4, -1, 2, 4, -1, 2, 4, -1, 2, 4], we first find all subarrays of length at least 2 where the first and last elements are equal. Then, we calculate the sum of each subarray and return the maximum sum.

Example 2
Input
[3, 1, 3, 1, 3]
Output
9

Explanation: Step-by-step: Given the input array [3, 1, 3, 1, 3], we first find all subarrays of length at least 2 where the first and last elements are equal. Then, we calculate the sum of each subarray and return the maximum sum.

Constraints

  • 2 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 2 <= k <= nums.length
  • There is at least one pair of indices (i, j) such that i < j, j - i + 1 >= k, and nums[i] == nums[j].
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

Maximum Equal-Endpoint Subarray Sum — Problem Statement & Solution Guide

ArraysMediumPrefix Sum
TimeO(N)
|
SpaceO(N)

Problem Description

Given an array of integers nums and an integer k, find the maximum sum of a contiguous subarray of length at least k such that the first and last elements of the subarray are equal.

Examples

Example 1

Input

[4, -1, 2, 4, -1, 2, 4, -1, 2, 4]

Output

12

Explanation: Step-by-step: Given the input array [4, -1, 2, 4, -1, 2, 4, -1, 2, 4], we first find all subarrays of length at least 2 where the first and last elements are equal. Then, we calculate the sum of each subarray and return the maximum sum.

Example 2

Input

[3, 1, 3, 1, 3]

Output

9

Explanation: Step-by-step: Given the input array [3, 1, 3, 1, 3], we first find all subarrays of length at least 2 where the first and last elements are equal. Then, we calculate the sum of each subarray and return the maximum sum.

Constraints

  • 2 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 2 <= k <= nums.length
  • There is at least one pair of indices (i, j) such that i < j, j - i + 1 >= k, and nums[i] == nums[j].

Optimal Approach & Strategy

We can optimize this to O(N) time and space using prefix sums and a hash map. As we iterate through the array with a pointer j (the end of our subarray), we can dynamically 'activate' candidate starting indices i = j - k + 1. We store the minimum prefix sum encountered for each unique value in our hash map. When we are at index j, we look up the minimum prefix sum of nums[j] in our hash map and compute the maximum possible sum ending at j.

Brute Force Approach

The brute force approach is to check every pair of indices (i, j) such that j - i + 1 >= k and nums[i] == nums[j]. For each valid pair, we compute the sum of the subarray from i to j using a nested loop or prefix sums. This takes O(N^2) time, which will result in a Time Limit Exceeded (TLE) error given the constraints.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function maxEqualEndpointSubarraySum(nums, k) {
  const n = nums.length;
  const P = new Array(n + 1).fill(0);
  for (let i = 0; i < n; i++) {
    P[i + 1] = P[i] + nums[i];
  }

  const minPref = new Map();
  let maxSum = -Infinity;

  for (let j = 0; j < n; j++) {
    const iNew = j - k + 1;
    if (iNew >= 0) {
      const v = nums[iNew];
      if (!minPref.has(v)) {
        minPref.set(v, P[iNew]);
      } else {
        minPref.set(v, Math.min(minPref.get(v), P[iNew]));
      }
    }

    const vJ = nums[j];
    if (minPref.has(vJ)) {
      const currSum = P[j + 1] - minPref.get(vJ);
      if (currSum > maxSum) {
        maxSum = currSum;
      }
    }
  }

  return maxSum;
}

Asked in Top Tech Interviews

Amazon

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.