(UVA) Subsequence - Solution
Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=3562
The solution below used a technique called Sliding Window to solve this problem.
import java.io.*;
import java.util.*;
class Main {
public void process() throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
while (sc.hasNext()) {
int numNumbers = sc.nextInt();
int desiredMinSum = sc.nextInt();
int sum = 0;
int pointerLeft = 0;
int minElements = Integer.MAX_VALUE;
int[] numbers = new int[numNumbers];
for (int pointerRight = 0; pointerRight < numNumbers; pointerRight++) {
numbers[pointerRight] = sc.nextInt();
sum += numbers[pointerRight];
while (sum >= desiredMinSum) {
minElements = Math.min(minElements, pointerRight-pointerLeft+1);
sum -= numbers[pointerLeft++];
}
}
minElements = (minElements == Integer.MAX_VALUE) ? 0 : minElements;
bw.write(minElements+"\n");
}
bw.flush();
bw.close();
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
The solution below used a technique called Sliding Window to solve this problem.
import java.io.*;
import java.util.*;
class Main {
public void process() throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
while (sc.hasNext()) {
int numNumbers = sc.nextInt();
int desiredMinSum = sc.nextInt();
int sum = 0;
int pointerLeft = 0;
int minElements = Integer.MAX_VALUE;
int[] numbers = new int[numNumbers];
for (int pointerRight = 0; pointerRight < numNumbers; pointerRight++) {
numbers[pointerRight] = sc.nextInt();
sum += numbers[pointerRight];
while (sum >= desiredMinSum) {
minElements = Math.min(minElements, pointerRight-pointerLeft+1);
sum -= numbers[pointerLeft++];
}
}
minElements = (minElements == Integer.MAX_VALUE) ? 0 : minElements;
bw.write(minElements+"\n");
}
bw.flush();
bw.close();
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
Comments
Post a Comment