https://www.hackerrank.com/challenges/game-of-two-stacks/problem
Solution (Java)
package com.anu.game;
import java.io.*;
import java.util.*;
public class Solution {
static int twoStacks(int x, int[] a, int[] b) {
int bIdx = 0;
int sumRemoved = 0;
while (bIdx < b.length && sumRemoved + b[bIdx] <= x) {
sumRemoved += b[bIdx];
bIdx++;
}
int numRemoved = bIdx;
for (int aIdx = 0; aIdx < a.length; aIdx++) {
sumRemoved += a[aIdx];
while (sumRemoved > x && bIdx > 0) {
bIdx--;
sumRemoved -= b[bIdx];
}
if (sumRemoved > x) {
break;
}
numRemoved = Math.max(numRemoved, aIdx + bIdx + 1);
}
return numRemoved;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("good"));
int g = Integer.parseInt(scanner.nextLine().trim());
for (int gItr = 0; gItr < g; gItr++) {
String[] nmx = scanner.nextLine().split(" ");
int n = Integer.parseInt(nmx[0].trim());
int m = Integer.parseInt(nmx[1].trim());
int x = Integer.parseInt(nmx[2].trim());
int[] a = new int[n];
String[] aItems = scanner.nextLine().split(" ");
for (int aItr = 0; aItr < n; aItr++) {
int aItem = Integer.parseInt(aItems[aItr].trim());
a[aItr] = aItem;
}
int[] b = new int[m];
String[] bItems = scanner.nextLine().split(" ");
for (int bItr = 0; bItr < m; bItr++) {
int bItem = Integer.parseInt(bItems[bItr].trim());
b[bItr] = bItem;
}
int result = twoStacks(x, a, b);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
}
bufferedWriter.close();
}
}