我试图解决这个问题http://www.spoj.com/problems/HOTELS/
我是这样做的
var A = [2, 1, 3, 4, 5];
var B = [];
var n = 5
var m = 12
big = -1;
for (i = 0; i <= n; i++) {
sum=0;
for (j = i; j <= n; j++) {
sum += A[j];
if (sum < m) { B[i] = sum; continue; }//B[i] становится равным сумме
if (sum > m) { B[i] = (sum - A[j]); break; }
if (sum == m) {
B[i] = sum //B[i] становится равным сумме
break;
}
}
if (B[i] > big)
big = B[i];
}
alert(big);
&#13;
现在我需要以某种方式通过&#34;提交解决方案&#34;在这里,我遇到了问题。如何正确更改我的代码以便我的决定被接受?
答案 0 :(得分:0)
您需要应用此算法
m
m
,请停止迭代并返回值。示例实施
var maxValue = 12;
[2, 1, 3, 4, 5].reduce( (a,c,i,ar) => {
a = a < maxValue ? Math.max( a, Math.max.apply( null, ar.slice( i ).map( ( s, ind ) => ar.slice( ind ).reduce( ( u, v ) => u + v, 0 ) ).filter( k => k <= maxValue ) ) ) : a;
return a;
}, 0);
<强>演示强>
var maxValue = 12;
var fnMaxConsecutive = ( arr, maxValue ) =>
arr.reduce( (a,c,i,ar) => {
a = a < maxValue ? Math.max( a, Math.max.apply( null, ar.slice( i ).map( ( s, ind ) => ar.slice( ind ).reduce( ( u, v ) => u + v, 0 ) ).filter( k => k <= maxValue ) ) ) : a;
return a;
}, 0);
console.log( fnMaxConsecutive ( [2, 1, 3, 4, 5], 12 ) );