We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Minimum Loss 1
- Discussions
Minimum Loss 1
Minimum Loss 1
Sort by
recency
|
12 Discussions
|
Please Login in order to post a comment
Java8 using TreeMap
Since similar solutions rely on either a sorted array or using binary search
n
times wheren
is the length of the array, the time complexity comes out toO(nlogn)
either way, I figured this is more intuitive:Proof of correctness of looking at min diff of only consecutive numbers (when their positions satisfy the requirement) in a sorted price list: suppose that we have prices
p1<p2<p3
where we assume thatp1,p3
is the optimal pair. In the original listp1
must appear afterp3
, and sincep1,p2
is not chosen as the optimal pair despitep2-p1<p3-p1
,p2
must appear afterp1
. Then we know thatp2
appears afterp3
andp3-p2<p3-p1
, and we should've chosenp2,p3
instead, contradiction.