Description
The input is List<Item> sorted by score, Item looks like:
class Item {
double score;
String category;
String author;
String poi;
}
Now I need to select 10 elements which have the highest scores from the array, under these limitations:
- They should have different
poi - They should have different
author - There are at most 3 items from the same
category. And the length of any subsequence from the samecategoryshould not be longer than 2.
If there is no subsequence which satisfies above rules, just return the first 10 elements.
What I have tried
Now, I directly iterate over the List, and use three HashMap<String, Integer> to store the appearences of each cagetory/poi/author. And I use List<Item> selected to store the result.
- If there is already a selected element that has this
poi, then the new element will be discarded. - If there is already a selected element that has this
author, then the new element will be discarded. - If there are already three selected elements that have this
category, then the new element will be discarded. - If there are already two elements in the tail of
selectedthat have thiscategory, then the new element will be discarded.
Problem
It works when the input is large, but when the input is relatively small, it does not work. For example, when the input is
- Item1(Category A, Author 1)
- Item2(Category A, Author 2)
- Item3(Category A, Author 3)
- Item4(Category B, Author 2)
- Item5(Category C, Author 5)
- Item6(Category D, Author 6)
- Item7(Category E, Author 7)
- Item8(Category F, Author 8)
- Item9(Category G, Author 9)
- Item10(Category H, Author 10)
- Item11(Category I, Author 11)
Then my solution will be
Item3discarded, because it has the samecategoryasItem1andItem2Item4discarded, because it has the sameauthorasItem2- the 9 other elements remain.
And this does not satisfy the select top 10 elements. The correct solution is discarding Item2 and only 10 elements should remain.
Question
I think my solution is just in the wrong direction. So I'm looking for other solutions to deal with this problem. Any solution produces the desired output is appreciated.