lyc0530
lyc0530

Reputation: 13

Find the minimum sum of two non-adjacent elements in an unsorted array in O(n) time?

input : {5,3,1,2,4,1}

output : 2

Is it possible to do this in O(N) time ?

Upvotes: 1

Views: 903

Answers (1)

PidgeyUsedGust
PidgeyUsedGust

Reputation: 817

You can find the three smallest elements in O(n), also storing their indices. At least two of those will be non-adjacent, so summing them will give the desired result.

Upvotes: 5

Related Questions