I'm trying to solve this problem from the Australian Informatics Olympiad here.
(These are past questions which I'm completing for the purpose of revision, if you are worried about the integrity of the competition, and unfortunately the organisation doesn't provide answers).
Basically, when given an input with: a list of "wet" or "dry" chairs, the number of people needed to be seated, and the number of people who will ONLY sit on dry chairs, you must determine the shortest possible distance between the two people on the ends (the shortest possible distance in total taken up by the group from first person to last).
The solution I found looped through each of the chairs, and for each wet chair allocated someone who was not picky, unless there were no more of those - in which case I simply skipped the chair. For each dry chair I allocated one picky person, or a non-picky person. There's quite a lot of looping - I've tried to refuse to the size of the data with certain conditional statements - however my solution still timed-out on many of the larger inputs (the max time allowed is 1 second for you code to complete), despite getting the correct outputs.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Solution {
public static void main(String[] args){
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader("chairsin.txt"));
String[] lineOne = bufferedReader.readLine().split(" ");
int numberOfChairs = Integer.parseInt(lineOne[0]);
int totalFriends = Integer.parseInt(lineOne[1]);
int niceFriends = Integer.parseInt(lineOne[2]);
int pickyFriends = totalFriends - niceFriends;
String[] chairs = bufferedReader.readLine().split("");
int shortestLength = numberOfChairs;
for(int x = 0; x < (chairs.length - totalFriends); x++){
int easyFriends = niceFriends;
int hardFriends = pickyFriends;
for(int y = x; y < chairs.length; y++){
if ((y - x + 1) > shortestLength){
break;
}
if(chairs[y].equalsIgnoreCase("w")){
if(easyFriends>0){
easyFriends--;
}
else
continue;
}
else{
if(hardFriends>0){
hardFriends--;
}
else if(easyFriends>0){
easyFriends--;
continue;
}
}
if(hardFriends == 0 && easyFriends == 0){
shortestLength = y - x + 1;
break;
}
}
}
PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter("chairsout.txt")));
printWriter.print(shortestLength);
bufferedReader.close();
printWriter.close();
}
catch (IOException exception) {
exception.printStackTrace();
}
}
}
Overall, I'm just looking for ways to improve my solution - be it by optimization, or using a completely different method/algorithm to solve this problem.
nWetUpTo[i]
be the number of wet seats up to and including position i. You can calculate this array quickly, and you can use it to tell you the number of wet seats between any two positions in just O(1) time :) \$\endgroup\$