你好,我需要在谷歌foobar项目的一个问题上寻求帮助,以下是我目前的进展。
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();
}
}
这是问题:
在维修太阳能电池板的时候,需要确定在任何给定阵列中可以离线维修哪些面板组,同时仍然保持每个阵列的最大功率输出。为了做到这一点,您首先需要确定每个阵列的最大输出。编写一个函数answer(xs),它接受代表数组中每个面板功率输出级别的整数列表,并返回其中某些非空子集的最大乘积。例如,如果一个数组包含功率输出级别为[2,-3,1,0,-5]的电池板,则通过取xs [0] = 2,xs [1] = -3,xs [4] = -5的子集来找到最大乘积,得到的乘积为2 *(-3)*(-5)= 30。因此,answer([2,-3,1,0,-5])将为“30”。
每组太阳能电池板至少包含1个且不超过50个面板,并且每个面板的功率输出级别的绝对值不大于1000(有些面板的故障很严重,它们正在消耗能量,但是您知道面板的波形稳定器技巧,可让你将两个负输出面板组合起来,以产生其功率值的多倍的正输出)。最终产品可能非常大,因此将答案作为数字的字符串表示给出。
语言
要提供Python解决方案,请编辑solution.py 要提供Java解决方案,请编辑solution.java
测试用例
Inputs:
(int list) xs = [2, 0, 2, 2, 0]
Output:
(string) "8"
Inputs:
(int list) xs = [-2, -3, 4, -5]
Output:
(string) "60"
我已经在进行这项工作两天了,希望能得到答案,以便我知道自己做错了什么并加以改进!感谢您的阅读,希望您能回答:)