【发布时间】:2017-10-20 09:25:58
【问题描述】:
我刚刚在 HackerRank 上尝试了一个基于堆栈的问题
https://www.hackerrank.com/challenges/game-of-two-stacks
Alexa 有两个非负整数堆栈,堆栈 A 和堆栈 B,其中索引 0 表示堆栈的顶部。 Alexa 挑战尼克玩以下游戏:
在每一步中,尼克可以从堆栈 A 或 B 堆栈的顶部移除一个整数。
Nick 保留他从两个堆栈中删除的整数的运行总和。
如果在任何时候,尼克的运行总和大于游戏开始时给出的某个整数 X,则尼克将被取消比赛资格。
Nick 的最终分数是他从两个堆栈中删除的整数总数。
找出尼克在每场比赛中可以达到的最大可能分数(即他可以在不被取消资格的情况下删除的最大整数数)并将其打印在新行上。
对于每场比赛,在新行上打印一个整数,表示尼克在不被取消资格的情况下可以达到的最高分。
Sample Input 0
1 -> Number of games
10 -> sum should not exceed 10
4 2 4 6 1 -> Stack A
2 1 8 5 -> Stack B
Sample Output
4
下面是我的代码,我尝试了贪婪的方法,从堆栈顶部获取最小元素并将其添加到总和中。它适用于某些测试用例,但在下面的输入中失败了
1
67
19 9 8 13 1 7 18 0 19 19 10 5 15 19 0 0 16 12 5 10 - Stack A
11 17 1 18 14 12 9 18 14 3 4 13 4 12 6 5 12 16 5 11 16 8 16 3 7 8 3 3 0 1 13 4 10 7 14 - Stack B
我的代码是5,但正确的解决方案是6,串联弹出的元素是19,9,8,11,17,1
堆栈 A 中的前三个元素和堆栈 B 中的前三个元素。
**
我不明白算法在我看来,任何人都可以使用 DP 帮我解决方法/算法?
**
public class Default {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int numOfGames = Integer.parseInt(br.readLine());
for (int i = 0; i < numOfGames; i++) {
String[] tmp = br.readLine().split(" ");
int numOfElementsStackOne = Integer.parseInt(tmp[0]);
int numOfElementsStackTwo = Integer.parseInt(tmp[1]);
int limit = Integer.parseInt(tmp[2]);
int sum = 0;
int popCount = 0;
Stack<Integer> stackOne = new Stack<Integer>();
Stack<Integer> stackTwo = new Stack<Integer>();
String[] stOne = br.readLine().split(" ");
String[] stTwo = br.readLine().split(" ");
for (int k = numOfElementsStackOne - 1; k >= 0; k--) {
stackOne.push(Integer.parseInt(stOne[k]));
}
for (int j = numOfElementsStackTwo - 1; j >= 0; j--) {
stackTwo.push(Integer.parseInt(stTwo[j]));
}
while (sum <= limit) {
int pk1 = 0;
int pk2 = 0;
if (stackOne.isEmpty()) {
sum = sum + stackTwo.pop();
popCount++;
} else if (stackTwo.isEmpty()) {
sum = sum + stackOne.pop();
popCount++;
}
else if (!stackOne.isEmpty() && !stackTwo.isEmpty()) {
pk1 = stackOne.peek();
pk2 = stackTwo.peek();
if (pk1 <= pk2) {
sum = sum + stackOne.pop();
popCount++;
} else {
sum = sum + stackTwo.pop();
popCount++;
}
} else if(stackOne.isEmpty() && stackTwo.isEmpty()){
break;
}
}
int score = (popCount>0)?(popCount-1):0;
System.out.println(score);
}
}
}
【问题讨论】:
-
当您收到的输出不正确时,我不确定您是否可以声称已解决问题。让别人把你的尝试变成正确的解决方案,这不是有点像作弊吗? :-) 但是您清楚地描述了问题、解决方案尝试和意外结果,因此您得到了我的投票。
-
我真的不认为这是作弊。这就是学习在你不理解的概念上借助社区的帮助。除了我不是参加比赛,这只是一个练习题
-
你注意到我赞成你的意见吗?
标签: java algorithm data-structures stack