How do you find the largest largest number of a given series of data. This question is being asked in many interviews and programming evaluation exercises and many developers actually failed to provide a simple answer. Hence thought of writing my point of view on this subject. Many times, developers think in complex ways when there is a simple solution to the problem. It is important remember the principle – “make it simple”.

Many people approach this problem as a sorting problem. But we didn’t ask to sort the numbers. The question is just to find the largest / biggest number. The logic using sorting is as follows, sort the series in the descending order and pick the first element. Of course the answer is correct, but you are wasting computing resources and performance. We don’t need to sort to find the bigger number. We just need to use a simple loop.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package com.javahash.sample; public class BiggestNumber { /** * @param args */ public static void main(String[] args) { int[] input={10,60,80,12,90,81,40,20}; int biggest=input[0]; for(int i=1;i<input.length;i++){ if(input[i] > biggest){ biggest=input[i]; } } System.out.println("Biggest number = "+biggest); } } |

This approach of using a simple for loop is also efficient as the time complexity of this method is only in the order of N ( Big Oh ( N) ). Typically sorting methodologies are in the order on N^2. Hence this method is simple and efficient.