VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-subarray-sum-of-prime-length/

⇱ Maximum Subarray sum of Prime length - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum Subarray sum of Prime length

Last Updated : 23 Jul, 2025

Given an array arr[] of size N, the task is to find the maximum subarray sum that can be obtained such that the length of the subarray should be prime.

Examples :

Input: arr[] = {2, -1, 3, -2, 1, -1} 
Output:
The subarray {2, -1, 3} of size = 3  (prime number)

input: arr[] = {-2, -3, 4, -1, -2, 1, 5, -3}
Output: 7
The subarray {4, -1, -2, 1, 5} of size = 5 (prime number)

Naive Approach:  The idea is as follows:

Generate all possible subarrays and from them find the ones with prime length. Find the maximum sum among them.

Follow the given steps to solve the problem:

  • Generate all possible subarrays of all lengths using nested for-loops.
  • Find the sum of each prime length subarray.
  • The numbers which are primes can be precomputed by Sieve algorithm 
  • Now for each prime length, calculate the sum and take the maximum of it    

Below is the implementation of the above approach:


Output
4

Time complexity: O(N3)
Auxiliary Space: O(N) 

Efficient Approach: To solve the problem follow the below idea:

Use Kadane's algorithm, and update the answer only if the length of the subarray is prime.

 Follow the given steps to solve the problem:

  • Initialize max_so_far = INT_MIN  (since sum can be negative), and max_ending_here = 0 (to keep track of the current sum )
  • Loop to iterate each element of the array:
    • max_ending_here is equal to max_ending_here + arr[i]
    • If max_so_far is less than max_ending_here then update max_so_far
    • If max_ending_here is less than 0 then set max_ending_here = 0
    • Return max_so_far
  • Now for calculating the subarray sum of prime length we have to keep track of the subarray size and have to check whether the size is prime or not 

Below is the implementation of the above idea :


Output
4

Time Complexity: O(N * log(logN))
Auxiliary Space: O(N)

Comment
Article Tags: