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

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...