Maximum sum of a Subarray with prime integers
Last Updated :
31 Jul, 2023
Given an array arr[] of integers of size n, find the maximum sum of a continuous subarray such that the subarray only contains prime integers. In other words, no non-prime integer should appear within the chosen subarray.
Examples:
Input: arr[] = [1, 7, 4, 2, 3, 8, 5, 11, 13], n = 9
Output: 29
Explanation: The subarray [5, 11, 13] is the only subarray with prime integers and with a maximum sum of 29.
Input: arr = [1, 4, 6, 7, 10], n = 5
Output: 7
Explanation: The maximum sum of a continuous subarray such that the subarray only contains prime integers is {7} with sum 7.
Naive Approach: The basic way to solve the problem is as follows:
The idea involves checking all possible subarrays that only contain prime integers and keeping track of the maximum sum.
Steps that were to follow the above approach:
- Initialize maxSum to 0
- Loop through all subarrays of arr
- Check if the current subarray only contains prime integers
- If it does, calculate its sum
- If its sum is greater than maxSum, update maxSum
- Return maxSum
Below is the code to implement the above steps:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPrime( int n)
{
if (n <= 1)
return false ;
for ( int i = 2; i <= sqrt (n); i++) {
if (n % i == 0)
return false ;
}
return true ;
}
int maxPrimeSubarraySum( int arr[], int n)
{
int maxSum = 0;
for ( int i = 0; i < n; i++) {
int currentSum = 0;
for ( int j = i; j < n; j++) {
if (isPrime(arr[j])) {
currentSum += arr[j];
maxSum = max(maxSum, currentSum);
}
else {
break ;
}
}
}
return maxSum;
}
int main()
{
int arr[] = { 1, 3, 5, 6, 7 };
int n = sizeof (arr) / sizeof (arr[0]);
int sum = maxPrimeSubarraySum(arr, n);
cout << "Maximum sum of prime subarray is: " << sum
<< endl;
return 0;
}
|
Java
import java.util.*;
public class Main {
public static boolean isPrime( int n)
{
if (n <= 1 )
return false ;
for ( int i = 2 ; i <= Math.sqrt(n); i++) {
if (n % i == 0 )
return false ;
}
return true ;
}
public static int maxPrimeSubarraySum( int [] arr, int n)
{
int maxSum = 0 ;
for ( int i = 0 ; i < n; i++) {
int currentSum = 0 ;
for ( int j = i; j < n; j++) {
if (isPrime(
arr[j])) {
currentSum += arr[j];
maxSum = Math.max(maxSum, currentSum);
}
else {
break ;
}
}
}
return maxSum;
}
public static void main(String[] args)
{
int [] arr = { 1 , 3 , 5 , 6 , 7 };
int n = arr.length;
int sum = maxPrimeSubarraySum(arr, n);
System.out.println(
"Maximum sum of prime subarray is: " + sum);
}
}
|
Python3
import math
def isPrime(n):
if n < = 1 :
return False
for i in range ( 2 , int (math.sqrt(n)) + 1 ):
if n % i = = 0 :
return False
return True
def maxPrimeSubarraySum(arr):
n = len (arr)
maxSum = 0
for i in range (n):
currentSum = 0
for j in range (i, n):
if isPrime(arr[j]):
currentSum + = arr[j]
maxSum = max (maxSum, currentSum)
else :
break
return maxSum
arr = [ 1 , 3 , 5 , 6 , 7 ]
sum = maxPrimeSubarraySum(arr)
print ( "Maximum sum of prime subarray is:" , sum )
|
C#
using System;
class GFG
{
static bool IsPrime( int n)
{
if (n <= 1)
return false ;
for ( int i = 2; i * i <= n; i++)
{
if (n % i == 0)
return false ;
}
return true ;
}
static int MaxPrimeSubarraySum( int [] arr, int n)
{
int maxSum = 0;
for ( int i = 0; i < n; i++)
{
int currentSum = 0;
for ( int j = i; j < n; j++)
{
if (IsPrime(arr[j]))
{
currentSum += arr[j];
maxSum = Math.Max(maxSum, currentSum);
}
else
{
break ;
}
}
}
return maxSum;
}
static void Main( string [] args)
{
int [] arr = { 1, 3, 5, 6, 7 };
int n = arr.Length;
int sum = MaxPrimeSubarraySum(arr, n);
Console.WriteLine( "Maximum sum of prime subarray is: " + sum);
}
}
|
Javascript
function isPrime(n) {
if (n <= 1)
return false ;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0)
return false ;
}
return true ;
}
function maxPrimeSubarraySum(arr) {
let n = arr.length;
let maxSum = 0;
for (let i = 0; i < n; i++) {
let currentSum = 0;
for (let j = i; j < n; j++) {
if (isPrime(arr[j])) {
currentSum += arr[j];
maxSum = Math.max(maxSum, currentSum);
} else {
break ;
}
}
}
return maxSum;
}
let arr = [1, 3, 5, 6, 7];
let sum = maxPrimeSubarraySum(arr);
console.log( "Maximum sum of prime subarray is: " + sum);
|
Output
Maximum sum of prime subarray is: 8
Time Complexity: O(N^2*sqrt(N)), since we are checking all possible subarrays and then checking if each integer in the subarray is prime.
Auxiliary Space: O(1), since we are not using any additional data structures.
Efficient Approach: To solve the problem using Hashmap follow the below steps:
- Inside the maxPrimeSubarraySum function, we initialize the variables maxSum, currentSum, start, and end.
- We then loop through the input array arr, incrementing the end variable each time.
- If the current element of arr is prime, we add it to currentSum, update maxSum if currentSum is greater, and move the start pointer forward.
- If the current element of arr is not prime, we subtract the prime integers from currentSum until the current element is no longer included in the subarray.
- We repeat steps 5-6 until we have looped through the entire array.
- Finally, we return the maxSum.
Below is the code to implement the above steps:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPrime( int n)
{
if (n <= 1)
return false ;
for ( int i = 2; i <= sqrt (n); i++) {
if (n % i == 0)
return false ;
}
return true ;
}
int maxPrimeSubarraySum( int arr[], int n)
{
unordered_map< int , int > freq;
int maxSum = 0, currentSum = 0;
for ( int i = 0; i < n; i++) {
if (isPrime(arr[i]))
{
currentSum += arr[i];
freq[arr[i]]++;
while (freq[arr[i]] > 1)
{
freq[arr[i - freq[arr[i]] + 1]]--;
currentSum -= arr[i - freq[arr[i]] + 1];
}
maxSum = max(maxSum, currentSum);
}
else
{
freq.clear();
currentSum = 0;
}
}
return maxSum;
}
int main()
{
int arr[] = { 1, 3, 5, 6, 7 };
int n = sizeof (arr) / sizeof (arr[0]);
int sum = maxPrimeSubarraySum(arr, n);
cout << "Maximum sum of prime subarray is: " << sum
<< endl;
return 0;
}
|
Java
import java.util.HashMap;
import java.util.Map;
public class Main {
public static boolean isPrime( int n)
{
if (n <= 1 )
return false ;
for ( int i = 2 ; i <= Math.sqrt(n); i++) {
if (n % i == 0 )
return false ;
}
return true ;
}
public static int maxPrimeSubarraySum( int [] arr, int n)
{
Map<Integer, Integer> freq
= new HashMap<>();
int maxSum = 0 , currentSum
= 0 ;
for ( int i = 0 ; i < n; i++) {
if (isPrime(
arr[i])) {
currentSum
+= arr[i];
freq.put(arr[i],
freq.getOrDefault(arr[i], 0 )
+ 1 );
while (
freq.get(arr[i])
> 1 ) {
freq.put(
arr[i - freq.get(arr[i]) + 1 ],
freq.get(
arr[i - freq.get(arr[i]) + 1 ])
- 1 );
currentSum
-= arr[i - freq.get(arr[i]) + 1 ];
}
maxSum = Math.max(
maxSum,
currentSum);
}
else {
freq.clear();
currentSum = 0 ;
}
}
return maxSum;
}
public static void main(String[] args)
{
int [] arr = { 1 , 3 , 5 , 6 , 7 };
int n = arr.length;
int sum = maxPrimeSubarraySum(
arr, n);
System.out.println(
"Maximum sum of prime subarray is: "
+ sum);
}
}
|
Python3
import math
def isPrime(n):
if n < = 1 :
return False
for i in range ( 2 , int (math.sqrt(n)) + 1 ):
if n % i = = 0 :
return False
return True
def maxPrimeSubarraySum(arr):
freq = {}
maxSum = 0
currentSum = 0
for i in range ( len (arr)):
if isPrime(arr[i]):
currentSum + = arr[i]
if arr[i] in freq:
freq[arr[i]] + = 1
else :
freq[arr[i]] = 1
while freq[arr[i]] > 1 :
freq[arr[i - freq[arr[i]] + 1 ]] - = 1
currentSum - = arr[i - freq[arr[i]] + 1 ]
maxSum = max (maxSum, currentSum)
else :
freq = {}
currentSum = 0
return maxSum
arr = [ 1 , 3 , 5 , 6 , 7 ]
sum = maxPrimeSubarraySum(arr)
print ( "Maximum sum of prime subarray is:" , sum )
|
C#
using System;
using System.Collections.Generic;
class Program
{
static bool IsPrime( int n)
{
if (n <= 1)
return false ;
for ( int i = 2; i <= Math.Sqrt(n); i++)
{
if (n % i == 0)
{
return false ;
}
}
return true ;
}
static int MaxPrimeSubarraySum( int [] arr, int n)
{
Dictionary< int , int > freq = new Dictionary< int , int >();
int maxSum = 0, currentSum = 0;
for ( int i = 0; i < n; i++)
{
if (IsPrime(arr[i]))
{
currentSum += arr[i];
if (!freq.ContainsKey(arr[i]))
{
freq[arr[i]] = 0;
}
freq[arr[i]]++;
while (freq[arr[i]] > 1)
{
freq[arr[i - freq[arr[i]] + 1]]--;
currentSum -= arr[i - freq[arr[i]] + 1];
}
maxSum = Math.Max(maxSum, currentSum);
}
else
{
freq.Clear();
currentSum = 0;
}
}
return maxSum;
}
static void Main( string [] args)
{
int [] arr = { 1, 3, 5, 6, 7 };
int n = arr.Length;
int sum = MaxPrimeSubarraySum(arr, n);
Console.WriteLine( "Maximum sum of prime subarray is: " + sum);
}
}
|
Javascript
function isPrime(n) {
if (n <= 1) {
return false ;
}
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
return false ;
}
}
return true ;
}
function maxPrimeSubarraySum(arr) {
const freq = new Map();
let maxSum = 0,
currentSum = 0;
for (let i = 0; i < arr.length; i++) {
if (isPrime(arr[i])) {
currentSum += arr[i];
freq.set(arr[i], (freq.get(arr[i]) || 0) + 1);
while (freq.get(arr[i]) > 1) {
freq.set(arr[i - freq.get(arr[i]) + 1], freq.get(arr[i] - 1));
currentSum -= arr[i - freq.get(arr[i]) + 1];
}
maxSum = Math.max(maxSum, currentSum);
} else {
freq.clear();
currentSum = 0;
}
}
return maxSum;
}
const arr = [1, 3, 5, 6, 7];
const sum = maxPrimeSubarraySum(arr);
console.log( "Maximum sum of prime subarray is:" , sum);
|
Output
Maximum sum of prime subarray is: 8
Time Complexity: O(N*sqrt(N)) because the function uses a single pass of the input array, and the operations performed in each iteration use sqrt(N) time in the prime function.
Auxiliary Space: O(N), because we used a hash map to store the indices of the unique prime numbers, encountered so far, and the hash table can potentially store all n elements of the input array.
Share your thoughts in the comments
Please Login to comment...