Java Algorithm
Date: Aug 2014
Level: Basic


INTERVIEW QUESTIONS

Company: Citrix Systems, Inc
Question Title: Java Algorithm
Language: Java
QUESTION DETAILS:

Given an array of positive and negative numbers, you need to find the maximum sum that we can achieve using this array. The only condition is that you cannot use two adjacent items.

Print sum in one line

Print all items that contribute to this sum in other line using space separated char. If all items are negative then print least negative no.
For example, consider this array:
-1 4 5 -2 -6 6
Output will be- 11
5 6


Here's the code:
public class Fonts{
public static void printMaxSum(int[] n){ 
if(n.length==0) 
System.out.println("array has no data"); 
else if (n.length==1){ 
System.out.println(n[0]); 
System.out.println(n[0]); 
}else if (n.length==2){ 
System.out.println(n[0] + n[1]); 
System.out.println(n[0] + " " + n[1]); 
}else{ 
int v1 = (n[0]>n[1])?n[0]:n[1]; 
int v2 = (n[0]>n[1])?n[1]:n[0]; 
for(int i=2; i<n.length;i++){ 
if(n[i]>v1){ 
v2=v1; 
v1=n[i]; 
}else if(n[i]<v1 && n[i]>v2){ 
v2=n[i]; 
} 
} 
System.out.println(v1 + v2); 
System.out.println(v2 + " " + v1); 
} 
}
public static void main(String[] args)
{
int [ ] num = {1, 4, 5, -2, -6, 6 };
printMaxSum(num);
}
}
All Questions