【发布时间】:2017-02-27 16:20:59
【问题描述】:
您好,我需要帮助解决我的一个 Google 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"
我已经用了 2 天了,我真的很想得到答案,这样我就可以了解我做错了什么并改进!感谢您的阅读,希望您能回答。 :)
【问题讨论】:
标签: java python arrays computer-science