在不超过总和K的情况下可以从两个堆栈的顶部移除的最大块数

问题描述

给出两个非负整数堆栈。计算在不超过总和K的情况下可以从堆栈顶部删除的最大整数数。假设如下图所示,给出了两个堆栈A和B。然后,如第二张图片所示,最多可以删除4个整数,而总和不超过 10 。如果需要,请在此处找到source

enter image description here

enter image description here

我尝试了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,(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,(currSum + peek));
        }
    }
    return Math.max(ansA,ansB);
}

解决方法

我相信您算法中的核心问题来自Stack的浅表副本。在以下代码段中:

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

您已经从堆栈A弹出,因此在ansB = 1 + solve(a,(currSum + peek));执行B的流程时,实际上是在传递经过修改的堆栈,而不是使用原始堆栈A。

另外,我认为这不是DP解决方案。我建议您进一步阅读。