我正在完成一个google foobar挑战,但对于我来说,我无法通过第四个测试用例,下面是挑战:
您需要找出任何给定阵列中的哪些电池组可以脱机修复,同时仍然保持每个阵列的最大功率输出量,要做到这一点,您首先需要找出每个阵列的最大输出是多少。编写一个函数answer(xs),该函数获取表示数组中每个面板的功率输出电平的整数列表,并返回这些数字的某个非空子集的最大乘积。因此,例如,如果一个数组包含功率输出电平为2、-3、1、0、-5的面板,则可以通过取以下子集来找到最大乘积:
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".
每个太阳能电池板阵列至少包含1块且不超过50块电池板,每个电池板都有一个功率输出电平,其绝对值不超过1000 (有些电池板故障严重,正在耗尽能量,但你知道电池板的稳波器的一个诀窍,它可以将两个负输出电池板组合在一起,产生电力值的倍数的正输出)。最终的乘积可能非常大,因此以数字的字符串表示形式给出答案。
以下是一些给定的测试用例:
测试用例
Inputs:
(int list) xs = [2, 0, 2, 2, 0]
Output:
(string) "8"
Inputs:
(int list) xs = [-2, -3, 4, -5]
Output:
(string) "60"下面是我的代码:
def product_of_values(lst):
product = 1
if len(lst) > 0:
for x in lst:
product *= x
return product
def answer(xs):
# two seperate list for positive and negative values
positive_list = [x for x in xs if x > 0]
negative_list = [x for x in xs if x < 0]
pos_product = product_of_values(pos_list)
# multiplication of an even number of negatives == positive value
if len(negative_list) % 2 == 0:
negative_product = product_of_values(negative_list)
# if length of negative_list is odd, pop value closest to zero
else:
neg_list.remove(max(neg_list))
neg_product = product_of_values(neg_list)
# If there is only one negative value in the negative_list, return 0.
if len(pos_list) < 1 and len(neg_list) <= 1:
return '0'
else:
return str(neg_product * pos_product)我是不是漏掉了什么明显的东西?
发布于 2020-06-14 06:27:56
@edi_allen我也面临着同样的问题。我已经用java写了代码,可见的测试用例在我的编译器中通过了,但在foobar失败了。你是如何克服这个问题的?下面是我的代码:
public static String solution(int[] xs) {
if(xs.length < 1 || xs.length > 50) {
return "0";
}
Arrays.parallelSort(xs);
for(int i = 1; i < xs.length ; i++) {
if(xs[i] < 0 && xs[i-1] < 0) {
xs[i-1] = Math.abs(xs[i-1]);
xs[i] = Math.abs(xs[i]);
}
}
BigInteger prod = null;
for(int i = 0; i < xs.length ; i++) {
if(Math.abs(xs[i]) > 1000) {
return "0";
}
else if(xs[i] <= 0) {
continue;
}
else if(prod == null){
prod = new BigInteger(String.valueOf(xs[i]));
}
else {
prod = prod.multiply(new BigInteger(String.valueOf(xs[i])));
}
}
if(prod == null) {
return "0";
}
return prod.toString();
}发布于 2016-11-12 09:27:14
也许这是时间复杂性的问题。
对于这个产品,试试这个-
from operator import mul
reduce(mul, list, 1)https://stackoverflow.com/questions/40558485
复制相似问题