Find the maximum product of negative numbers in Java
I'm taking a semi - advanced course in Java I taught myself JavaScript as a hobby, so I'm not a real beginner, but I'm not very experienced in making algorithms We have a homework problem to do It follows the following way: given n positive integers, where n > = 5, find the possible maximum product by selecting two (not necessarily continuous) numbers as factors
For example, if the input is: 3 6 0 10 4, the output should be 60
It seems quite easy I just picked the two largest ones and multiplied them:
System.out.println("How many numbers will you give me?"); int n = sc.nextInt(); if (n < 5) throw new Error("n must be at least 5"); System.out.println("Enter the numbers"); int max1 = 0,max2 = 0; for (int i = 0; i < n; ++i) { int newInt = sc.nextInt(); if (newInt > max1) { max2 = max1; max1 = newInt; } else if (newInt > max2) { max2 = newInt; } } System.out.println("The largest product is " + (max1 * max2));
This is very effective Now, after that, there is a "reward" or extension problem (optional) I decided to give it a try The problem is similar: given an integer of n (not necessarily a positive number), find the largest product by selecting two (not necessarily continuous) numbers as factors Assuming 5 < = n < = 25, the program should run within a reasonable time. The problem with the old program is that the input will fail, such as - 6 - 5 3 0 4 When the correct answer is 30, it will output 12 I decided to check the absolute value instead of the actual value, so negative numbers will be included The code is similar to:
System.out.println("How many numbers will you give me?"); int n = sc.nextInt(); if (n < 5) throw new Error("n must be at least 5"); System.out.println("Enter the numbers"); int max1 = 0,max2 = 0; for (int i = 0; i < n; ++i) { int newInt = sc.nextInt(),absValue = Math.abs(newInt); if (absValue > Math.abs(max1)) { max2 = max1; max1 = newInt; } else if (absValue > Math.abs(max2)) { max2 = newInt; } } System.out.println("The largest product is " + (max1 * max2));
This applies to - 6 - 5 3 0 4, giving 30 correctly, but - 6 - 3 1 5 4 fails It gives an answer of - 30, which is obviously incorrect
I tried a powerful solution (check every possible product), which is very good for n = 5, but needs n! Iteration, which means that n = 25 takes a long time It's hard for me to understand how to solve this problem Thank you first
Solution
The problem is that checking absolute values discards information that may be negative You need two positive numbers or two negative numbers
The easiest way to achieve this is to scan and find the two smallest and two largest numbers
The smallest two of several Multiply by the two largest ones Whichever is more your result