91bd
91bd Given an array 91bd arr[] 91bd of dimension 91bd N 91bd , the duty is to 91bd seek out the utmost subarray 91bd sum that may be obtained 91bd such that the size of 91bd the subarray must be prime.
91bd Examples :
91bd Enter: 91bd arr[] = {2, -1, 91bd 3, -2, 1, -1}
91bd Output: 91bd 4
91bd The subarray {2, -1, 3} 91bd of dimension = 3 (prime 91bd quantity)91bd enter: 91bd arr[] = {-2, -3, 4, 91bd -1, -2, 1, 5, -3}
91bd Output: 91bd 7
91bd The subarray {4, -1, -2, 91bd 1, 5} of dimension = 91bd 5 (prime quantity)
91bd
91bd Naive Strategy: 91bd The concept is as 91bd follows:
91bd Generate all doable subarrays and 91bd from them discover those with 91bd prime size. Discover the utmost 91bd sum amongst them.
91bd Comply with the given steps 91bd to unravel the issue:
- 91bd Generate all doable subarrays of 91bd all lengths utilizing nested for-loops.
- 91bd Discover the sum of every 91bd prime size subarray.
- 91bd The numbers that are primes 91bd will be precomputed by 91bd Sieve algorithm
- 91bd Now for every prime size, 91bd calculate the sum and take 91bd the utmost of it 91bd
91bd Beneath is the implementation of 91bd the above method:
91bd C++14
|
91bd Time complexity: 91bd O(N 91bd 3 91bd )
91bd Auxiliary Area: 91bd O(N)
91bd Environment friendly Strategy: 91bd To unravel the issue comply 91bd with the beneath concept:
91bd Use Kadane’s algorithm, and replace 91bd the reply provided that the 91bd size of the subarray is 91bd prime.
91bd Comply with the given steps 91bd to unravel the issue:
- 91bd Initialize max_so_far = INT_MIN (since 91bd sum will be destructive), and 91bd max_ending_here = 0 (to maintain 91bd monitor of the present sum 91bd )
- 91bd Loop to iterate every factor 91bd of the array:
- 91bd max_ending_here is the same as 91bd max_ending_here + arr[i]
- 91bd If max_so_far is lower than 91bd max_ending_here then replace max_so_far
- 91bd If max_ending_here is lower than 91bd 0 then set max_ending_here = 91bd 0
- 91bd Return max_so_far
- 91bd Now for calculating the subarray 91bd sum of prime size now 91bd we have to maintain monitor 91bd of the subarray dimension and 91bd should verify whether or not 91bd the scale is prime or 91bd not
91bd Beneath is the implementation of 91bd the above concept :
91bd C++14
|
91bd Time Complexity: 91bd O(N * log(logN))
91bd Auxiliary Area: 91bd O(N)
91bd