![]() |
VOOZH | about |
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: 4
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:
Below is the implementation of the above approach:
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:
Below is the implementation of the above idea :
4
Time Complexity: O(N * log(logN))
Auxiliary Space: O(N)