Multiple occurrences

You are given an integer array A. Your task is to calculate the sum of absolute difference of indices of first and last occurrence for every integer that is present in array A.

Formally, if element x occurs m times in the array at indices B1, B2, B3, ...,Bm, then the answer for x will be BmB1 if array B is sorted.

You are required to calculate the sum of the answer for every such x that occurs in the array.

Refer to sample notes and explanations for better understanding.

Example:

Input: N=5, arr[] = { 1, 2, 3, 3, 2 };
Output: 4

Approach

Java


import java.util.HashMap;

public class MultipleOccurrences {
    public static void main(String args[]) {
        int NN = 5;
        int arr[] = { 12332 };
        HashMap<LongIntegerindexes = new HashMap<LongInteger>();
        long sum = 0;
        for (int i = 0; i < NN; i++) {
            long A_i = arr[i];
            if (indexes.containsKey(A_i)) {
                sum = sum + i - indexes.get(A_i);
            }
            indexes.put(A_i, i);
        }
        System.out.println(sum);
    }

}


No comments:

Post a Comment