I was given this question in an OA and couldnt solve it in time. I thought it was interesting and solved it 3 hours latter.
Find the minimum number of groups who's sum of each group is at max 3, and every element must be in a group.
Given an Array like: [1.01, 1.01, 3.0, 2.7, 1.99, 2.3, 1.7]
return the minimum number of groups, in this case it would be 5 groups: (1.01 , 1.99), (1.01, 1.7), (3.0), (2.7), (2.3)
Constraint: all elements are between 1.01-3 inclucsive, and each groups sum is at max 3
My Solution:
I recomend trying to solve this one your self.
The naive aproach would be to find all posible choices and choose the sequence of choices that has the least groups, and to do this would require some backtracking which I want to avoid at all costs cause im bad also I think O(n!) time complextiy and maybe O(n!) space not sure.
My aproach is O(n*logn) and O(1) extra space.
Here is some psudo code. I never ran it so it actualy may not work :P
leftIndex = 0
totalGroups=0
arr.sort() #first sort the array
iterate from end to beggining
if arr[i]>1.99:
totalGroups+=1 #add to total groups since it is impossible to extend a group containg value 2, since the minimum element size is 1.01 and 2+1.01 is 3.01 which is not allowed since max group size is 3
if arr[i]=<1.99: #otherwise it is possible to find a group
if arr[ leftIndex ]+arr[i] <= 3: # since the array is sorted we want to match the biggest element, which is our current element since were iterating backwords, with our smallest element which is at leftindex, this technique counts the minimum pairs that can be made that are <=3
leftIndex +=1 #if there is a match we dont want to double count so we incremnet the left index
totalGroups+=1
stop when leftIndex > i #we need to stop when we have checked all pairs
return totalGroupsI know the code can be compressed, but I think it will help with understanding better becase that is how i thought of it.
Also I solved this by drawing the process out.