Find all triplets in array with sum less than or equal to given sum

后端 未结 5 2193
星月不相逢
星月不相逢 2020-12-15 10:57

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?

5条回答
  •  鱼传尺愫
    2020-12-15 11:52

    From a worst-case asymptotic perspective, there is no better algorithm since the size of the output is potentially O(n3).

    e.g. Let the array be the numbers 1 through n. Let S = 3n. Clearly, any subset of three array elements will be less than S and there are (n choose 3) = O(n³) subsets.

    There are a few ways you can speed up non-worst cases though. For example, try sorting the array first. That should give you some hints.

提交回复
热议问题