// Java program for the above approach
import java.util.*;
class GFG {
// Function to find the minimum number
// of jumps required to sort the array
static void minJumps(int[] w, int[] l, int n)
{
// Base Case
if (n == 1) {
System.out.print(0);
return;
}
// Store the required result
int ans = 0;
// Stores the current position of
// elements and their respective
// maximum jump
HashMap<Integer, Integer> pos
= new HashMap<Integer, Integer>();
HashMap<Integer, Integer> jump
= new HashMap<Integer, Integer>();
// Used to check if a position is
// already taken by another element
HashMap<Integer, Boolean> filled
= new HashMap<Integer, Boolean>();
// Stores the sorted array a[]
int[] a = new int[n];
// Traverse the array w[] & update
// positions jumps array a[]
for (int i = 0; i < n; i++) {
if (pos.containsKey(w[i]))
pos.put(w[i], i);
else
pos.put(w[i], i);
if (filled.containsKey(w[i]))
filled.put(i, true);
else
filled.put(i, true);
if (jump.containsKey(w[i]))
jump.put(w[i], l[i]);
else
jump.put(w[i], l[i]);
a[i] = w[i];
}
// Sort the array a[]
Arrays.sort(a);
// Traverse the array a[] over
// the range [1, N-1]
for (int curr = 1; curr < n; curr++) {
// Store the index of current
// element and its just smaller
// element in array w[]
int currElementPos = pos.get(a[curr]);
int prevElementPos = pos.get(a[curr - 1]);
if (currElementPos > prevElementPos)
continue;
// Iterate until current element
// position is at most its just
// smaller element position
while (currElementPos <= prevElementPos
|| filled.containsKey(currElementPos)
&& filled.containsKey(
currElementPos)) {
currElementPos += jump.get(a[curr]);
ans++;
}
// Update the position of the
// current element
if (pos.containsKey(a[curr]))
pos.put(a[curr], currElementPos);
else
pos.put(a[curr], currElementPos);
if (filled.containsKey(currElementPos))
filled.put(currElementPos, true);
else
filled.put(currElementPos, true);
}
// Print the result
System.out.print(ans);
}
// Driver Code
public static void main(String[] args)
{
int[] W = { 2, 1, 4, 3 };
int[] L = { 4, 1, 2, 4 };
int N = W.length;
minJumps(W, L, N);
}
}
// This code is contributed by ukasp.