Skip to content

Instantly share code, notes, and snippets.

@aire-con-gas
Created May 7, 2019 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aire-con-gas/e93326fe6469d301f9fd4100cfa12af6 to your computer and use it in GitHub Desktop.
Save aire-con-gas/e93326fe6469d301f9fd4100cfa12af6 to your computer and use it in GitHub Desktop.
CarFueling - my solution to a programming exercise
import java.util.*;
import java.io.*;
public class CarFueling {
static int computeMinRefills(int dist, int tank, int[] stops) {
int numOfRefills = 0;
int currentIdx = 0;
int lastRefillIdx = 0;
while (currentIdx < stops.length - 1) {
lastRefillIdx = currentIdx;
while (currentIdx < stops.length && currentIdx + 1 < stops.length && stops[currentIdx + 1] - stops[lastRefillIdx] < tank) {
currentIdx = currentIdx + 1;
}
if (currentIdx == lastRefillIdx) {
return -1;
}
if (currentIdx < stops.length - 1) {
numOfRefills = numOfRefills + 1;
}
}
return numOfRefills;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int dist = scanner.nextInt();
int tank = scanner.nextInt();
int n = scanner.nextInt() + 2;
int stops[] = new int[n];
stops[0] = 0;
for (int i = 1; i < n - 1; i++) {
stops[i] = scanner.nextInt();
}
stops[n - 1] = dist;
System.out.println(computeMinRefills(dist, tank, stops));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment