I found this problem a bit more involved in terms of coding for an easy problem. Lucky with LINQ the code is relatively compact but I think people competing with other languages could have find it a bit long.
From the requirements, we must listen at least T songs from each album. So we return -1 if there not at least T songs in each album.
We can now calculate the minimum time needed to listen T songs from each album. Obviously we take the shortest songs from each album to minimize this number. If this time is greater than the allowed time we return -1. Note that we must convert the minutes in seconds!
At this point, we know that we can at least listen 2 * T songs that in total takes time seconds.
Now, we don’t have any album constraints so we can listen the next shortest song from any of the two albums. We can do this until we have enough time.
We can take the two durations array, remove the first T songs, concatenate them and sort the result. In this way we have the remaining list of songs ordered by duration. We then iterate through the list, adding each duration to the time and counting the listened songs.
Follow the complete implementation:
- Use Contact() to concatenate two sequences and keep duplicates.
- Use Union() to concatenate two sequences and remove duplicates. I made this silly mistake during the competition and I failed system tests 🙁
- LINQ made implementing this problem so much easier. I invite you to try doing it in Java.