I have to find the maximum sum in an array such that no 3 consecutive number together for eg 3 4 5 1 2 should return me 11. (4+5+2)
I am getting out as 9. I am using dynamic programming since I want the running time to be O(N) The idea is s array will store the max sum and s1 array will store the length of input seen to keep track of consecuent numbers
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class ex {
public static int maxSubArraySum(int a[], int size)
{
int s[]= new int[size+1];
s[0]=0;
int s1[]= new int[size+1];
s1[0]=0;
for (i = 1; i <= size; i++)
{
s1[i]= 1+s1[i-1];
if(s1[i]<3) {
int k=Math.max(s[i-1], a[i-1]+s[i-1]);
s[i]=k;
}
else {
s[i]=Math.max(a[i-1], a[i-1]+a[i]);
s1[i]=0;
}
}
return s[s.length-1];
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc= new Scanner(System.in);
int size=sc.nextInt();
int a[]=new int[size];
for(int i=0;i<size;i++) {
a[i]=sc.nextInt();
}
System.out.println(maxSubArraySum(a, a.length));
}
}