Problem statement: Find the largest product of any two numbers in a list
Input - a list of numbers
Output - the largest product of any 2 numbers in the list
e.g. - [1 7 3 4 2 6 5] => 42
Input - a list of numbers
Output - the largest product of any 2 numbers in the list
e.g. - [1 7 3 4 2 6 5] => 42
- public class ProductOfLargestNum {
- public static void main(String[] args) {
- int a[] = { 1, 7, 3, 4, 2, 6, 5 };
- int temp;
- /*
- * logic is to sort the list first then get last and last but one
- * element and do the product
- */
- // bubble sort algorithm
- for (int i = 0; i < a.length; i++) {
- for (int j = 0; j < a.length - 1; j++) {
- if (a[j] > a[j + 1]) {
- temp = a[j];
- a[j] = a[j + 1];
- a[j + 1] = temp;
- }
- }
- }
- System.out.println("list after sorting");
- for (int i : a) {
- System.out.print(i + " ");
- }
- int last = a[a.length - 1];
- int lastButOne = a[a.length - 2];
- System.out.println();
- System.out.println(last * lastButOne);
- }
- }
Output:
list after sorting
1 2 3 4 5 6 7
42
No comments:
Post a Comment