Length of a valley

You are given an integer array A consisting of N elements. For each element, you are required to find the length of the valley that is defined as:

Let i be the current index and l and r be the leftmost and rightmost index satisfying this property a[l]>a[l+1].....>a[i1]>a[i]<a[i+1]<...a[r1]<a[r], then (rl+1) is the length of the valley. Also, assume that if A is [7,2,1,5,7,9], then the answer is [1,2,6,3,2,1].

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 = (int5e5 + 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[] = { 721579 };
        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];
            else
                l[i] = i;
            if (a[j] < a[j + 1])
                r[j] = r[j + 1];
            else
                r[j] = j;
        }
        for (int i = 1; i <= n; ++i) {
            System.out.print((r[i] - l[i] + 1) + " ");
        }
    }

}


No comments:

Post a Comment