Advertisement
Guest User

Untitled

a guest
Mar 26th, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. /*
  2. * Write a function to find the max sum of two numbers from a list of numbers
  3. * eg1: [1,2,3,4,5] => 9
  4. * eg2: [10,30 ,20,-5, 5] => 50
  5. */
  6. import java.io.*;
  7. public class Test
  8. {
  9. public static void main(String args[])
  10. {
  11. int numberArray[] = new a[1,2,3,4,5];
  12. int result=sumofMaxTwoNumbers(numberArray);
  13. System.out.println("The maximum sum of two numbers is: " + result);
  14. }
  15.  
  16. public static int sumOfMaxTwoNumbers(int input[])
  17. {
  18. if(input==null)
  19. {
  20. return 0;
  21. }
  22.  
  23. if(input.length==0)
  24. {
  25. return 0;
  26. }
  27. int maxNumber=input[0];
  28. int secondMaxNumber=0;
  29. for(int i=0;i<input.length-1;i++)
  30. {
  31. if(input[i+1]>maxNumber)
  32. {
  33. maxNumber=input[i+1];
  34. }
  35. }
  36. if(input[0]==maxNumber)
  37. {
  38. secondMaxNumber=input[1];
  39. }
  40. else
  41. {
  42. secondMaxNumber=input[0];
  43. }
  44.  
  45. for(int j=0;j<input.length-1;j++)
  46. {
  47. if((input[j]!=maxNumber)&&((input[j]>secondMaxNumber))
  48. {
  49. secondMaxNumber=input[j];
  50. }
  51. }
  52. return maxNumber+secondMaxNumber;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement