You are given an integer array consisting of elements. For each element, you are required to find the length of the valley that is defined as:
Let be the current index and and be the leftmost and rightmost index satisfying this property , then is the length of the valley. Also, assume that if is , then the answer is .
Example:
Input: n=6, arr[] = { 7, 2, 1, 5, 7, 9 }
Output: 1 2 6 3 2 1
Approach
Java
public class LengthOFValley {public static void main(String[] args) {final int N = (int) 5e5 + 2;int a[] = new int[N];int l[] = new int[N], r[] = new int[N];a[0] = Integer.MIN_VALUE;int n = 6;int arr[] = { 7, 2, 1, 5, 7, 9 };for (int i = 1; i <= n; ++i) {a[i] = arr[i - 1];}a[n + 1] = Integer.MIN_VALUE;for (int i = 1, j = n; i <= n; ++i, --j) {if (a[i - 1] > a[i])l[i] = l[i - 1];elsel[i] = i;if (a[j] < a[j + 1])r[j] = r[j + 1];elser[j] = j;}for (int i = 1; i <= n; ++i) {System.out.print((r[i] - l[i] + 1) + " ");}}}
No comments:
Post a Comment