java—可从两个堆栈的顶部移除的最大块数,且不超过k之和

s4chpxco  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(286)

给定两个非负整数堆栈。计算在不超过k和的情况下可以从堆栈顶部移除的最大整数数。假设两个堆栈a和b如下图所示。然后,如第二个图像中所描述的,最多可以移除4个整数,而不超过总和10。如果需要,请在这里找到来源。


我试着用dp方法来解决这个问题。但我只能通过几个测试。有人能告诉我出了什么问题吗。

static int maxStacks(int maxSum, int[] a, int[] b) {
    Stack<Integer> stackA = new Stack<>();
    Stack<Integer> stackB = new Stack<>();
    for(int i=a.length-1;i>=0;i--) {
        stackA.push(a[i]);
    }
    for(int i=b.length-1;i>=0;i--) {
        stackB.push(b[i]);
    }
    return solve(stackA, stackB, maxSum, 0);
}

static int solve(Stack<Integer> a, Stack<Integer> b, int maxSum, int currSum) {
    if(a.isEmpty() && b.isEmpty()) {
        return 0;
    }
    int ansA;
    if(a.isEmpty()) {
        ansA = 0;
    } else {
        int peek = a.peek();
        if((currSum + peek) > maxSum) {
            ansA = 0;
        } else {
            a.pop();
            ansA = 1 + solve(a, b, maxSum, (currSum + peek));
        }
    }
    int ansB;
    if(b.isEmpty()) {
        ansB = 0;
    } else {
        int peek = b.peek();
        if((currSum + peek) > maxSum) {
            ansB = 0;
        } else {
            b.pop();
            ansB = 1 + solve(a, b, maxSum, (currSum + peek));
        }
    }
    return Math.max(ansA, ansB);
}
zsohkypk

zsohkypk1#

我相信你的算法的核心问题来自堆栈的浅拷贝。在以下代码段中:

} else {
            a.pop();
            ansA = 1 + solve(a, b, maxSum, (currSum + peek));
        }

您已经从堆栈a中弹出,因此当在执行b的流时 ansB = 1 + solve(a, b, maxSum, (currSum + peek)); ,而不是使用原始堆栈a,实际上是传递修改后的堆栈。
另一方面,我认为这不是dp解决方案。我建议你多读一读。

相关问题