I recently took an Amazon OA and had the exact same question as this problem https://aonecode.com/interview-question/load_cargo.
I done a similar problem like this before and even input my code to the online judge on this website. I got all test cases right with my code but on the assessment, I passed only 4/13 cases. I am wondering if I am missing something or maybe it was looking for an efficient answer? Please let me know if there is anything wrong with my code or ways to improve it!
Overall idea of my method:
public int solution(int num, int[] containers, int itemSize, int[] itemsPerContainer, int cargoSize){
int max = 0;
Map<Integer, Integer> map = new HashMap<>();
Comparator<Entry<Integer, Integer>> valueComparator = new Comparator<Entry<Integer,Integer>>() {
@Override
public int compare(Entry<Integer, Integer> m1, Entry<Integer, Integer> m2) {
return m2.getValue().compareTo(m1.getValue());
}
};
for(int i = 0; i < containers.length; i++) {
map.put(i, itemsPerContainer[i]);
}
List<Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, valueComparator);
for(Entry<Integer, Integer> x: list) {
cargoSize -= containers[x.getKey()];
max += x.getValue() * containers[x.getKey()];
if(cargoSize <= 0) {
max -= x.getValue()*Math.abs(cargoSize);
break;
}
}
return max;
}