Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Write a function to find the max sum of two numbers from a list of numbers
- * eg1: [1,2,3,4,5] => 9
- * eg2: [10,30 ,20,-5, 5] => 50
- */
- import java.io.*;
- public class Test
- {
- public static void main(String args[])
- {
- int numberArray[] = new a[1,2,3,4,5];
- int result=sumofMaxTwoNumbers(numberArray);
- System.out.println("The maximum sum of two numbers is: " + result);
- }
- public static int sumOfMaxTwoNumbers(int input[])
- {
- if(input==null)
- {
- return 0;
- }
- if(input.length==0)
- {
- return 0;
- }
- int maxNumber=input[0];
- int secondMaxNumber=0;
- for(int i=0;i<input.length-1;i++)
- {
- if(input[i+1]>maxNumber)
- {
- maxNumber=input[i+1];
- }
- }
- if(input[0]==maxNumber)
- {
- secondMaxNumber=input[1];
- }
- else
- {
- secondMaxNumber=input[0];
- }
- for(int j=0;j<input.length-1;j++)
- {
- if((input[j]!=maxNumber)&&((input[j]>secondMaxNumber))
- {
- secondMaxNumber=input[j];
- }
- }
- return maxNumber+secondMaxNumber;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement