The maximum distance

You are given an array a1, a2, , aN consisting of N elements. You are given Q queries. Each query is of the following types:

  1. The format of the first type of query is 1 L R x. You must increase the values of all elements in range L to R (both inclusive) by integer x.
  2. The format of the second type of query is 2 L R y. You must multiply the values of all elements in range L to R (both inclusive) by the integer y.
  3. The format of the third type of query is 3 z. You are required to find the maximum distance between elements that are equal to z in the array. If the element is not present in the array, print -1.

Example:

Input:
5 1 2 3 4 5 5 1 1 2 1 2 1 4 3 3 9 1 5 5 1 3 6
Output:
2
5

Approach

Java


public class MaximumDistance {
    public static void main(String[] args) {
        int n = 5;
        long[] arr = { 12345 };
        int q = 5;
        int query[][] = { { 1121 }, { 2143 }, { 39 }, { 1551 }, { 36 } };
        for (int i = 0; i < q; i++) {
            int type = query[i][0];
            switch (type) {
            case 1:
            case 2:
                update(arr, type, query[i][1] - 1, query[i][2] - 1, query[i][3]);
                break;
            default:
                System.out.println(find(arr, n, query[i][1]));
            }
        }
    }

    static private int find(long[] arrint nlong finder) {
        int left = 0, right = n - 1;
        boolean found = false;
        while (left < right) {
            if (arr[left] == finder) {
                found = true;
                break;
            }
            left += 1;
        }
        while (right > left) {
            if (arr[right] == finder) {
                found = true;
                break;
            }
            right -= 1;
        }
        if (!found)
            return -1;
        return right - left + 1;
    }

    static private void update(long[] arrint typeint lint rlong x) {
        for (int i = l; i <= r; i++) {
            if (type == 1) {
                arr[i] += x;
            } else
                arr[i] *= x;
        }
    }

}


No comments:

Post a Comment