Description:
Find top two maximum numbers in an array
Code:
package com.techonol.algos; public class MaxTwoNumbers { public void printTwoMaxNumbers(int[] nums) { int maxOne = 0; int maxTwo = 0; for (int n : nums) { if (maxOne < n) { maxTwo = maxOne; maxOne = n; } else if (maxTwo < n) { maxTwo = n; } } System.out.println("1st Max. Number: " + maxOne); System.out.println("2nd Max. Number: " + maxTwo); } public static void main(String a[]) { int num[] = { 55, 105, 78, 2, 87, 1, 99, 23 }; MaxTwoNumbers mn = new MaxTwoNumbers(); mn.printTwoMaxNumbers(num); } }
Output:
1st Max. Number: 105 2nd Max. Number: 99