Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Monday, July 31, 2017

Max Sum without Adjacents




Here we need to keep track on previous exlude value and use it in formula.
We are taking two integer one where we include number and one where exclude.

Code:

import java.util.*;
import java.lang.*;
import java.io.*;
class hackerranksloutionc
 {
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
   int n=ab.nextInt();
   
   int arr[]=new int[n];
   for(int i=0;i<n;i++)
   arr[i]=ab.nextInt();
   int include=arr[0];
   int exclude=0;
   int newexclude=0;
   for(int i=1;i<n;i++)
   {
       newexclude=Math.max(exclude,include);
       include=exclude+arr[i];
       exclude=newexclude;
   }
   System.out.println(Math.max(exclude,include));
}
}
}

0 Comments:

Post a Comment

Stats