Dan*_*ang 6 javascript algorithm dynamic-programming kadanes-algorithm
我正在尝试找到关于子阵列最小切片的编码问题的解决方案,并且我已经设计了一个使用Kadane算法的修改版本的解决方案.我目前已经获得90/100并且设法通过O(n)中的几乎所有测试.但是,我似乎无法通过"medium_range,增加,减少(legth = ~100)和小功能,得到5预期3",我不知道为什么.这可能是解决方案的重复,但我使用的方法略有不同.
我的逻辑如下:
a)如果我们有一个数组MinA,其中MinA [k]表示从k开始的子阵列的最小平均切片,最小长度为2
b)然后,如果我们循环通过MinA并找到数组的最小值,那么这将是整个数组的最小平均切片(然后返回索引位置)
c)创建这个MinA,我们从数组的倒数第二个元素开始,MinA [A.length -2]是A的最后两个元素的平均值
d)我们将柜台向左移动一个位置; MinA [计数器]必须是A [计数器]和A [计数器+ 1]的平均值或元素计数器的平均值和MinA [counter + 1]中的元素
e)如果d不为真,那么这意味着MinA [counter + 1]不是从计数器+ 1到从计数器+ 2到N的某个元素的最小平均切片
我想知道我是否遗漏了什么?
/*
* Using modified version of Kadane's algorithm
* The key logic is that for an array A of length N,
* if M[k + 1] is the minimum slice of a subarray from k + 1 to any element
* between k+2 to n, then M[k] is either the average of A[k] and A[k + 1], or
* the average of the elements k and the elements in M[k + 1]
*/
function solution(A) {
// you can use console.log for debugging purposes, i.e.
// console.log('this is debug message');
// write your code in JavaScript (ECMA-262, 5th edition)
var minSliceArray = [],
counter = A.length - 2,
currMinSliceLength = 0,
min = Number.POSITIVE_INFINITY,
minIndex = -1;
minSliceArray[counter] = (A[counter] + A[counter + 1]) / 2;
currMinSliceLength = 2;
counter--;
while (counter >= 0) {
var a = (A[counter] + A[counter + 1]) / 2,
b = (A[counter] + minSliceArray[counter + 1] * currMinSliceLength) / (currMinSliceLength + 1) ;
if (a < b) {
minSliceArray[counter] = a;
currMinSliceLength = 2;
} else {
minSliceArray[counter] = b;
currMinSliceLength++;
}
counter--;
}
//loops through the minSliceArray and find the minimum slice
for (var i = 0; i < minSliceArray.length; i++) {
if (minSliceArray[i] < min) {
min = minSliceArray[i];
minIndex = i;
}
}
return minIndex;
}
Run Code Online (Sandbox Code Playgroud)
要解决您的问题,您可以替换代码
if (a < b) {
Run Code Online (Sandbox Code Playgroud)
和
if (a <= b) {
Run Code Online (Sandbox Code Playgroud)
例如A = [-3, 3, -3, 3, -3],首先我们考虑的是A[3:5],平均值为0。然后,我们来到位置2,A[2: 5]/3 = -1,A[2:4]/2 = 0,所以我们选择前者。对于位置 1,A[1:3]/2 == A[1:5]/4 == 0。在OLD答案中,我们应该继续选择 A[1:5]。最后对于位置 0,我们有 A[0:2]/2 = 0,并且 A[0:5]/5 = -0.6 我们选择后者。毕竟,整体最小平均值位于位置 3,因为 A[3:5]/3=-1。但实际上 A[0:3]/3 == -1 == A[3:5]/3。
因为这样的陷阱,我在我的博客中没有使用Kadane算法的修改版本。但它应该工作得很好。