How far have you gotten in Greedy (1)

Minho Jang
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

resource: link

Solution

  1. Make an n-length array with an int type.
  2. 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)
  3. 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.

--

--

Minho Jang
Minho Jang

Written by Minho Jang

Backend Developer, Writer, and Lifelong Learner

No responses yet