【发布时间】:2016-03-10 02:17:39
【问题描述】:
这是一个问题: codility.com/programmers/task/number_solitaire
下面的链接是我的结果(50% 来自 Codility): https://codility.com/demo/results/training8AMJZH-RTA/
我的代码(起初,我尝试使用 Kadane 的算法解决这个问题):
class Solution {
public int solution(int[] A) {
int temp_max = Integer.MIN_VALUE;
int max = 0;
int k = 1;
if(A.length == 2) return A[0] + A[A.length-1];
for(int i = 1; i < A.length-1; i++) {
if(temp_max < A[i]) temp_max = A[i];
if(A[i] > 0) {
max += A[i];
temp_max = Integer.MIN_VALUE;
k = 0;
} else if(k % 6 == 0) {
max += temp_max;
temp_max = Integer.MIN_VALUE;
k = 0;
}
k++;
}
return A[0] + max + A[A.length-1];
}
以下是我从网上找到的解决方案(100% 来自 Codility 结果):
class Solution {
public int solution(int[] A) {
int[] store = new int[A.length];
store[0] = A[0];
for (int i = 1; i < A.length; i++) {
store[i] = store[i-1];
for (int minus = 2; minus <= 6; minus++) {
if (i >= minus) {
store[i] = Math.max(store[i], store[i - minus]);
} else {
break;
}
}
store[i] += A[i];
}
return store[A.length - 1];
}
}
我不知道我的代码有什么问题:(
我尝试了几个测试用例,但解决方案和我的代码没有什么不同
但是,代码测试结果显示我的并不完全正确。 (https://codility.com/demo/results/training8AMJZH-RTA/)
请任何人解释我的代码的问题~~
【问题讨论】: