How far have you gotten in Greedy (1)
1 min readDec 23, 2020
Greedy Algorithm: an algorithm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious and immediate benefit. So the problems where choosing locally optimal also leads to the global solution are best fit for Greedy. — GeeksForGeeks
Question
Solution
- Make an n-length array with an int type.
- Loop both arrays of teams with damaged kayaks and the teams with reserve kayaks and change each team’s status. (-1 if damaged, +1 if reserved)
- Check the team in order. If a team has only a damaged kayak, see if the previous team or the next team has a reserve. If so, move the kayak to the team.
Answer Code
Review
Difficult to deal with the restriction. Using a HashSet can be one other way to remove the duplicates between the damaged and the reserve. In Java, however, importing the HashSet is trickier than in python so that I chose this method using an index, which, as a result, looks simpler and clearer.