This was recently asked to a friend in an interview and we do not know of any solution other than the simple O(n3) one.
Is there some better algorithm?
The question is to find all triplets in an integer array whose sum is less than or equal to given sum S.
Note: I have seen other such problems on SO with performance O(n2log n) but all of them were solving the easier version of this problem like where arr[i] + arr[j] + arr[k] = S
or where they were only checking whether one such triplet exists.
My question is to find out all i,j,k
in arr[]
such that arr[i] + arr[j] + arr[k] <= S
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…