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

前端 未结 13 1020
小蘑菇
小蘑菇 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 03:58

    Elaborating on the above answer, you'd need a modified insertion-sort to track the smallest four values and the corresponding indexes (an array of 4 elements for each).

    Once found the solution would be the first pair whose difference in indexes would be more than 1 and whose sum is the least.

    The solution being one of (0,1) or (0,2) or (0,3) or (1,2) or (1,3) or (2,3) where the values indicate the indexes of the array that in turn tracks the position of the actual elements in the array.

    Also you'd need to handle the special case for array-length 5 (arr\[1]+arr[3]) and an error for those arrays less than 5.

提交回复
热议问题