gpt4 book ai didi

javascript - 如何解决编码minMaxDivision

转载 作者:行者123 更新时间:2023-12-05 00:35:32 25 4
gpt4 key购买 nike

我一直在尝试解决 1H30 的这个 codility 问题,以及如何使用二进制搜索来解决。我找到了答案,但我无法理解其背后的逻辑。得到它的人可以引导我完成这个答案。
这是问题

Task description

You are given integers K, M and a non-empty zero-indexed array Aconsisting of N integers. Every element of the array is not greaterthan M.

You should divide this array into K blocks of consecutive elements.The size of the block is any integer between 0 and N. Every element ofthe array should belong to some block.

The sum of the block from X to Y equals A[X] + A[X + 1] + ... + A[Y].The sum of empty block equals 0.

The large sum is the maximal sum of any block.

For example, you are given integers K = 3, M = 5 and array A suchthat:

A[0] = 2 A[1] = 1 A[2] = 5 A[3] = 1 A[4] = 2 A[5] = 2
A[6] = 2

The array can be divided, for example, into the following blocks:

[2, 1, 5, 1, 2, 2, 2], [], [] with a large sum of 15; [2], [1, 5, 1,2], [2, 2] with a large sum of 9; [2, 1, 5], [], [1, 2, 2, 2] with alarge sum of 8; [2, 1], [5, 1], [2, 2, 2] with a large sum of 6.

The goal is to minimize the large sum. In the above example, 6 is theminimal large sum.

Write a function:

function solution(K, M, A);

that, given integers K, M and a non-empty zero-indexed array Aconsisting of N integers, returns the minimal large sum.

For example, given K = 3, M = 5 and array A such that:

A[0] = 2 A[1] = 1 A[2] = 5 A[3] = 1 A[4] = 2 A[5] = 2
A[6] = 2

the function should return 6, as explained above.

Assume that:

N and K are integers within the range [1..100,000];M is an integer within the range [0..10,000];each element of array A is an integer within the range [0..M].


这是我可以得到的答案
function solution(K, M, A) {
var begin = A.reduce((a, v) => (a + v), 0)
begin = parseInt((begin+K-1)/K, 10);
var maxA = Math.max(A);
if (maxA > begin) begin = maxA;

var end = begin + M + 1;
var res = 0;

while(begin <= end) {
var mid = (begin + end) / 2;
var sum = 0;
var block = 1;
for (var ind in A) {
var a = A[ind];
sum += a;
if (sum > mid) {
++block;
if (block > K) break;
sum = a;
}
}
if (block > K) {
begin = mid + 1;
} else {
res = mid;
end = mid - 1;
}
}
return res;
}

最佳答案

这是 binary search关于解决方案。对于每个候选解决方案,我们迭代整个数组一次,将数组 block 填充到 block 在超过候选之前可以达到的最大总和。如果总和无法实现,则尝试较小的总和是没有意义的,因此我们搜索更高可能候选者的空间。如果总和是可以实现的,我们会尝试较低候选人的空间,而我们可以。

关于javascript - 如何解决编码minMaxDivision,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64681831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com