Sunday, May 13, 2018

Find the largest product of any two numbers in a list

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
  1. public class ProductOfLargestNum {
  2. public static void main(String[] args) {

  3. int a[] = { 1, 7, 3, 4, 2, 6, 5 };
  4. int temp;
  5. /*
  6. * logic is to sort the list first then get last and last but one
  7. * element and do the product
  8. */
  9.    // bubble sort algorithm
  10. for (int i = 0; i < a.length; i++) {
  11. for (int j = 0; j < a.length - 1; j++) {
  12. if (a[j] > a[j + 1]) {
  13. temp = a[j];
  14. a[j] = a[j + 1];
  15. a[j + 1] = temp;
  16. }
  17. }
  18. }
  19. System.out.println("list after sorting");
  20. for (int i : a) {
  21. System.out.print(i + " ");
  22. }
  23. int last = a[a.length - 1];
  24. int lastButOne = a[a.length - 2];
  25. System.out.println();
  26. System.out.println(last * lastButOne);
  27. }
  28. }
Output:
list after sorting
1 2 3 4 5 6 7 

42

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...