Picking five numbers that sum to S

前端 未结 4 1570
孤街浪徒
孤街浪徒 2021-01-31 10:51

Given an array A of N nonnegative numbers, I\'m interested in finding the number of ways you can pick 5 numbers (from distinct positions in the array)

4条回答
  •  清歌不尽
    2021-01-31 11:17

    O(N^3) seem possible (though I haven't tried proving it).

    Take all possible pairs and create a new array (say B) of size O(N^2) which holds the sum of all possible pairs. Also keep track of the index of two elements from the original array which gave that sum. - O(N^2)

    Now sort the array - O(N^2LogN).

    Now for each element a in the original array, try to find two elements from B which sum to S-a. Since B is sorted this can be done in O(B) time: Start with two pointers, one at the max and one at the min.

    If Sum of those two > S-a, decrement the pointer near max.

    If Sum of those two < S-a, increment the pointer near min.

    If the sum is equal, then you have found one candidate pair and a new sorted sub-array in which to look for the next possible candidate pair. (You should ensure that the two elements of B come from four elements of A). (There might be potential issues here)

    Thus you can count the number of times S-a occurs as a sum of two elements of B, which come from four elements of the original array (not including a).

    So O(N^2) time for O(N) elements - O(N^3).

    Hope that helps.

提交回复
热议问题