Finding two non-subsequent elements in array which sum is minimal

前端 未结 13 1013
小蘑菇
小蘑菇 2021-02-05 03:40

Intro: As far as I could search, this question wasn\'t asked in SO yet.
This is an interview question.
I am not even specifically looking for a code sol

13条回答
  •  别那么骄傲
    2021-02-05 04:05

    Use dynamic programming.

    1. Remove or disregard the first and last elements of your array. Since they cannot participate in the solution, they are not important. Once you've done this, you can also ignore the "must not be the first or last element" constraint since we've already accounted for it.
    2. Find the solution for the first three elements of (what's left of) the array (and without considering the "no first/last element" rule). There is only one solution in this case (array[0] + array[2]), so this is a trivial step.
    3. Memoize the minimal element which is not the last element (i.e. min(array[0], array[1])).
    4. Find the solution for the first four elements. We don't have to redo the whole problem; instead we just have to ask whether introducing the fourth element allows us to produce a smaller solution. We can do this by adding the fourth element to the minimal element we memoized in the previous step, and comparing the sum to the solution we found in the second step.
    5. Update the memoized minimal element so that it is the minimum of the first three elements.
    6. Continue widening and updating in this fashion until we have considered the entire array.

    The whole algorithm is O(n), since both widening and updating are constant-time operations. The algorithm can be proved correct by simple induction. O(n) is also a lower bound since we have to consider every element of the array, so this algorithm is optimal.

提交回复
热议问题