You are given an integer array . 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 .
Formally, if element occurs times in the array at indices , then the answer for will be if array is sorted.
You are required to calculate the sum of the answer for every such 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[] = { 1, 2, 3, 3, 2 };HashMap<Long, Integer> indexes = new HashMap<Long, Integer>();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