You are given an array consisting of elements. You are given queries. Each query is of the following types:
- The format of the first type of query is . You must increase the values of all elements in range to (both inclusive) by integer .
- The format of the second type of query is . You must multiply the values of all elements in range to (both inclusive) by the integer .
- The format of the third type of query is . You are required to find the maximum distance between elements that are equal to 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 6Output:25
Approach
Java
public class MaximumDistance {public static void main(String[] args) {int n = 5;long[] arr = { 1, 2, 3, 4, 5 };int q = 5;int query[][] = { { 1, 1, 2, 1 }, { 2, 1, 4, 3 }, { 3, 9 }, { 1, 5, 5, 1 }, { 3, 6 } };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[] arr, int n, long 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[] arr, int type, int l, int r, long x) {for (int i = l; i <= r; i++) {if (type == 1) {arr[i] += x;} elsearr[i] *= x;}}}
No comments:
Post a Comment