Google Foobar power_hungry

爱⌒轻易说出口 提交于 2020-05-29 07:25:08

问题


Hello I need help with one of my Google foobar questions this is what I've got so far.

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;
        int[] negatives = new int[xsLen];
        if (xsLen == 1){
            return Integer.toString(xs[0]);
        }
        // Split the input up into pos/negative. Pos get put onto the final value, as they don't need anything else.
        // they are all useful. negative to onto seperate array and get sorted later
        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)));
            } else {
                negatives[pos] = val;
                pos++;
            }
        }
        // even number of negatives means a full product will always be positive.
        // odd number means that we discard the smallest number to maximise the result.
        if ((pos % 2) == 0){
            // even number, so add to result
            for (int i = 0;i < pos;i++){
                result = result.multiply(new BigInteger(Integer.toString(negatives[i])));
            }
        } else {
            // sort then discard the minimum
            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])));
            }
        }

        // done, return the string;
        return result.toString();
    }
}

here's the question,

You need to figure out which sets of panels in any given array you can take offline to repair while still maintaining the maximum amount of power output per array, and to do THAT, you'll first need to figure out what the maximum output of each array actually is. Write a function answer(xs) that takes a list of integers representing the power output levels of each panel in an array, and returns the maximum product of some non-empty subset of those numbers. So for example, if an array contained panels with power output levels of [2, -3, 1, 0, -5], then the maximum product would be found by taking the subset: xs[0] = 2, xs[1] = -3, xs[4] = -5, giving the product 2*(-3)*(-5) = 30. So answer([2,-3,1,0,-5]) will be "30".

Each array of solar panels contains at least 1 and no more than 50 panels, and each panel will have a power output level whose absolute value is no greater than 1000 (some panels are malfunctioning so badly that they're draining energy, but you know a trick with the panels' wave stabilizer that lets you combine two negative-output panels to produce the positive output of the multiple of their power values). The final products may be very large, so give the answer as a string representation of the number.

Languages

To provide a Python solution, edit solution.py To provide a Java solution, edit solution.java

Test cases

Inputs:
    (int list) xs = [2, 0, 2, 2, 0]
Output:
    (string) "8"

Inputs:
    (int list) xs = [-2, -3, 4, -5]
Output:
    (string) "60"

I've been at it for 2 days and would really like the answer so I can learn what I have done wrong and improve! Thanks for reading and hopefully you answer. :)


回答1:


You need to Handle certain cases:

your array has between 1 and 50 Integer elements ranging from -1000 to 1000. what if your input was like this: [0, 0, -43, 0]. In that case,

    if (xsLen == 1){
        return Integer.toString(xs[0]);
    }

Doesn't make sense. (You can't have a negative answer). your answer should be 0 in this case.

The key to solving this problem is to recognize that You can Multiply two negative integers to get a positive one. BigInteger is useful because your final answer may get really really large.

The Way I implemented the solution is that I multiplied every non-zero Integer and stored the value as a BigInteger result variable. However, I kept another variable to keep track of "Greatest negative integer". At the end divide the result by your "Greatest Negative Integer" variable and there you have your answer.

I kept a count of Positive Integers and a count of Negative Integers... Hope this helps.




回答2:


Your code is good but just you have to do a minor addition such that if all elements in array are zero or negative then it should return 0. so here is the code.

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();
}
}



回答3:


try to make code that satisfies these test cases or similar. {-2} -> -2

{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 {

public static String result(int[] xs) {

// System.out.println("Hello World"); int i = 0,j;

    String pwr = "1";

    Arrays.sort(xs);
    while(i < xs.length && xs[i] < 0 ){
        i++;
    }
    if(i != 0){
        if (i == 1){
            if(xs[xs.length - 1] == 0){
                pwr = "0";
            } else if (xs.length == 1){
                return Arrays.valueOf(xs[0]);
            }
        }
        else if(i % 2 == 0){
            for (j = 0; j < i ;j++ ) {
                pwr = multiply(pwr, String.valueOf(xs[j]));
            }
        } else {
            for (j = 0; j < i - 1; j++ ) {
                pwr = multiply(pwr, String.valueOf(xs[j]));
            }
        }
    } else {
        if(xs[xs.length - 1] == 0){
            pwr = "0";
        }
    }

    for(;i < xs.length; i++){
        if(xs[i] != 0)
            pwr = multiply(pwr, String.valueOf(xs[i]));
    }


    return (pwr);     
}

public static String multiply(String num1, String num2){
                String tempnum1 = num1; 
                String tempnum2 = num2; 

                // Check condition if one string is negative 
                if(num1.charAt(0) == '-' && num2.charAt(0)!='-') 
                { 
                    num1 = num1.substring(1); 
                } 
                else if(num1.charAt(0) != '-' && num2.charAt(0) == '-') 
                { 
                    num2 = num2.substring(1); 
                } 
                else if(num1.charAt(0) == '-' && num2.charAt(0) == '-') 
                { 
                    num1 = num1.substring(1); 
                    num2 = num2.substring(1); 
                } 
                String s1 = new StringBuffer(num1).reverse().toString(); 
                String s2 = new StringBuffer(num2).reverse().toString(); 

                int[] m = new int[s1.length()+s2.length()]; 

                        // Go from right to left in num1 
                for (int k = 0; k < s1.length(); k++)  
                { 
                    // Go from right to left in num2 
                    for (int j = 0; j < s2.length(); j++)  
                    { 
                        m[k+j] = m[k+j]+(s1.charAt(k)-'0')*(s2.charAt(j)-'0'); 

                    } 
                } 


                String product = new String(); 
                // Multiply with current digit of first number 
                // and add result to previously stored product 
                // at current position.  
                for (int l = 0; l < m.length; l++) 
                { 
                    int digit = m[l]%10; 
                    int carry = m[l]/10; 
                    if(l+1<m.length) 
                    { 
                        m[l+1] = m[l+1] + carry; 
                    } 
                    product = digit+product; 

                } 

                // ignore '0's from the right 
                while(product.length()>1 && product.charAt(0) == '0') 
                { 
                    product = product.substring(1); 
                } 

                // Check condition if one string is negative 
                if(tempnum1.charAt(0) == '-' && tempnum2.charAt(0)!='-') 
                { 
                    product = new StringBuffer(product).insert(0,'-').toString(); 
                } 
                else if(tempnum1.charAt(0) != '-' && tempnum2.charAt(0) == '-') 
                { 
                    product = new StringBuffer(product).insert(0,'-').toString(); 
                } 
                else if(tempnum1.charAt(0) == '-' && tempnum2.charAt(0) == '-') 
                { 
                    product = product; 
                } 
                // System.out.println("Product of the two numbers is :"+"\n"+product); 
                return product;
}

}



来源:https://stackoverflow.com/questions/40107461/google-foobar-power-hungry

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!