algorithm - Find largest product of negative numbers in Java -
i taking semi-advanced class in java. taught myself javascript hobby, i'm not real beginner, i'm not experienced when comes making algorithms. have homework problem do. goes along lines of: given n positive integers, n >= 5 find largest product possible picking 2 (not consecutive) numbers factors.
for example, if input is: 3 6 0 10 4
, output should 60
.
this seemed easy. picked largest 2 , multiplied them:
system.out.println("how many numbers give me?"); int n = sc.nextint(); if (n < 5) throw new error("n must @ least 5"); system.out.println("enter numbers"); int max1 = 0, max2 = 0; (int = 0; < 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 " + (max1 * max2));
this worked perfectly. now, there "bonus" or extended problem after 1 (optional). decided try it. problem similar: given n (not positive) integers, find largest product possible picking 2 (not consecutive) numbers factors. program should run in reasonable amount of time, given 5 <= n <= 25
the problem old program fail inputs -6 -5 3 0 4
. ouput 12
when correct answer 30
. decided check absolute values instead of actual values, negative numbers included. code went like:
system.out.println("how many numbers give me?"); int n = sc.nextint(); if (n < 5) throw new error("n must @ least 5"); system.out.println("enter numbers"); int max1 = 0, max2 = 0; (int = 0; < 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 " + (max1 * max2));
this worked -6 -5 3 0 4
, correctly giving 30
failed -6 -3 1 5 4
. gave answer of -30
incorrect.
i tried brute force solution, (checking every possible product) worked n = 5
requires n!
iterations, means takes long time n = 25
. i'm stumped on how solve problem. thank in advance.
the problem checking absolute value throws away information may negative. need either 2 positive or 2 negative numbers.
the simplest way achieve scan through, find 2 smallest , 2 largest numbers.
multiple 2 smallest. multiply 2 largest. whichever of bigger result.
Comments
Post a Comment