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

前端 未结 13 1006
小蘑菇
小蘑菇 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:12

    1. Find the smallest number beside the first and the last.
    2. Find the second smallest that is not a neighbour of the first one and not the first or last one in the array. Then build the sum.

      • If the first element is the second or the penultimate element you already have the solution.
    3. Otherwise calculate the sum of both neighbours of the first number. check if its smaller then the first sum

      • if not: take the first sum
      • otherwise take the second one

    This will always work because if the first sum is not the answer that means the first number cannot be part of the solution. And that on the other hand means, the solution can just be the second sum.

提交回复
热议问题