How to power-hungry foobar solution in java (Java Programming Language)
The challenge is to find the maximum product of a subset of a given array. Here's the problem:
My code basically removes all 0's inside the list, then I iterate over all the remaining integers in the array and put each one in their respective array (positive or negative numbers). I sort my array with negative numbers then check its length; if it's odd, then I remove the last element (which will always be the one closest to 0 since I sorted it). Finally, I multiply each number inside these two arrays and return the result (we need to return it as string).
I've already search the internet as to why my logic is failing the fourth test case, I've read that if there's only one negative number in the array, you should return 0, but I also read that you should return the negative value. However, previously to writing the part of my code that checks this possibility, the fifth test case was also failing. So you need to return 0 in this case.
Here's the repl with my code, open test cases and some test cases that I've added.
{2,3,2,2} -> 24
{-2,-2,-3} -> 6
{-2,-2,-2,-3} -> 24
{-2,-2,0,0,-2,-3} -> 24
{2,3,0,0,2,2} -> 24
{-2,-2,0,0,2,3} -> 24
{0,0} -> 0
and also in foobar challenge the size of the result to return will 10^50 might be possible.
So it is also recommended to implement a product using String.
import java.util.Arrays;
public class Main {
package com.google.challenges;
import java.math.BigInteger;
public class Answer {
public static String answer (int[] xs){
BigInteger result = new BigInteger(1);
int xsLen = xs.length, pos = 0,ng=0;
int[] negatives = new int[xsLen];
if (xsLen == 1){
return Integer.toString(xs[0]);
}
for (int n = 0;n < xsLen;n++){
int val = xs[n];
if (val == 0){
continue;
}
if (val > 0){
result = result.multiply(new BigInteger(Integer.toString(val)));
ng++;
} else {
negatives[pos] = val;
pos++;
}
}
if(ng==0)
{
int l=0;
return Integer.toString(l);
}
if ((pos % 2) == 0){
for (int i = 0;i < pos;i++){
result = result.multiply(new BigInteger(Integer.toString(negatives[i])));
}
} else {
int min = -1000; int mPos = -1;
for (int i = 0;i < pos;i++){
if(negatives[i] > min){
min = negatives[i];
mPos = i;
}
}
for (int j = 0;j < pos;j++){
if(j == mPos){
continue;
}
result = result.multiply(new BigInteger(Integer.toString(negatives[j])));
}
}
return result.toString();
}
}
Source: StackOverFlow
More Questions
- How to disable gionee push?
- How to permanently freeze panes in excel?
- What is overseas economic transfer bureau?
- What is Treeview tv customer care number?
- How to deactivate ooredoo passport?
- What is gc transfer?
- How to stop auto renew gx12?
- What is Mxq pro 4k customer care number?
- What is transfer out admin equity?
- What is memorandum trading account?