BackmediumArraysOracleAtlassian

Maximum Prefix Subarray Sum Solution

Problem Statement

Given an array of integers arr and a prefix array prefix, find the maximum sum of a subarray that starts with the given prefix.

Example 1
Input
[1, 2, 3, 4, 5], [1]
Output
15

Explanation: Step-by-step: Given the array [1, 2, 3, 4, 5] and prefix [1], we slide the window from the prefix to the end of the array. The maximum sum of subarray starting with prefix [1] is 15, which is the sum of subarray [1, 2, 3, 4, 5].

Example 2
Input
[1, 2, 3, 4, 5], [1, 2]
Output
6

Explanation: Step-by-step: Given the array [1, 2, 3, 4, 5] and prefix [1, 2], we slide the window from the prefix to the end of the array. The maximum sum of subarray starting with prefix [1, 2] is 6, which is the sum of subarray [1, 2].

Constraints

  • 1 <= array.length <= 10^5
  • -10^4 <= array[i] <= 10^4
  • 1 <= prefix.length <= 10^5
  • The prefix is a contiguous subarray of the given array
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 Prefix Subarray Sum — Problem Statement & Solution Guide

ArraysMediumKadane's / Prefix Sum
TimeO(n)
|
SpaceO(1)

Problem Description

Given an array of integers arr and a prefix array prefix, find the maximum sum of a subarray that starts with the given prefix.

Examples

Example 1

Input

[1, 2, 3, 4, 5], [1]

Output

15

Explanation: Step-by-step: Given the array [1, 2, 3, 4, 5] and prefix [1], we slide the window from the prefix to the end of the array. The maximum sum of subarray starting with prefix [1] is 15, which is the sum of subarray [1, 2, 3, 4, 5].

Example 2

Input

[1, 2, 3, 4, 5], [1, 2]

Output

6

Explanation: Step-by-step: Given the array [1, 2, 3, 4, 5] and prefix [1, 2], we slide the window from the prefix to the end of the array. The maximum sum of subarray starting with prefix [1, 2] is 6, which is the sum of subarray [1, 2].

Constraints

  • 1 <= array.length <= 10^5
  • -10^4 <= array[i] <= 10^4
  • 1 <= prefix.length <= 10^5
  • The prefix is a contiguous subarray of the given array

Verified Code Solutions

JavaScript Solution
Time: O(n)
function maxPrefixSubarraySum(arr, prefix) {
  if (prefix.length > arr.length) return -Infinity;
  let maxSum = -Infinity;
  let currentSum = 0;
  let prefixIndex = 0;
  for (let i = 0; i < arr.length; i++) {
    if (i >= prefix.length) break;
    if (prefix[prefixIndex] !== arr[i]) {
      currentSum = 0;
      prefixIndex++;
    }
    currentSum += arr[i];
    maxSum = Math.max(maxSum, currentSum);
    if (currentSum < 0) currentSum = 0;
  }
  return maxSum;
}

Asked in Top Tech Interviews

OracleAtlassian

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.