title: Jumping to next closest element
body: <p>Given an array of N elements, numbered from 1 to N. The ith element has value V[i]. Also all elements are distinct.</p>
  
  <p>To move from ith to jth element we need to spend a cost of |i-j|.
  But we can jump from ith to jth element only if : </p>
  
  <ol>
  <li><p>j is not closer than K positions from key i (i.e. j should not be in the range [ i-K+1, i+K-1 ]).</p></li>
  <li><p>V[j] &lt; V[i].</p></li>
  </ol>
  
  <p>Each element may have 0 or more elements that can be jumped to.</p>
  
  <p>We need to find the summation of cost required to go from each element i to the closest element that can be jumped after it. If there is no next element to which we can jump for a element i, then consider its cost as 0.</p>
  
  <p>Example : Let N=5 and K=1 and array be [3,5,4,2,1] then here answer is 6</p>
  
  <p>Explanation :</p>
  
  <pre><code>The next jumping elements for:
  1 is { }. Closest=none, so cost = 0
  2 is { 1 }. Closest=1, so cost = 1
  3 is { 1 , 2 }. Closest=2, so cost = 3
  4 is { 1 , 2 , 3 }. Closest=2, so cost= 1
  5 is { 1 , 2 , 3 , 4 }. Closest=3 or 4, so cost = 1
  </code></pre>
  
  <p>Total cost is 6</p>
  
  <p>I know a brute solution that will run in O(N^2). But 1 &lt;= N &lt;= 2 * 10^5 and 1 &lt;= K,V[i] &lt;= N. So what can be better way to solve this problem ?</p>