Length of a valley
Practice
3.1 (61 votes)
Dynamic programming
Algorithms
Introduction to dynamic programming 1
Problem
92% Success 7068 Attempts 30 Points 2s Time Limit 256MB Memory 1024 KB Max Code

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[i-1]>a[i]<a[i+1]<... a[r-1]<a[r]\), then \((r-l+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]\).

Explanation

  • A1 (7): The answer is 1 because there is no element to the left and in right 2 is smaller than 7.
  • A2 (2): A1>A2, therefore, the answer is 2
  • A(1): A1>A2>A3<A4<A5<A6, therefore, the answer is 6
  • A4 (5): A4<A5<A6, therefore, the answer is 3
  • A5 (7): A5<A6, therefore, the answer is 2
  • A6 (9): 7 is smaller than 9 and there is no element to the right, therefore, the answer is 1

Input format

  • The first line contains an integer \(T\) denoting the number of test cases. 
  • The first line of each test case contains an integer \(N\) denoting the number of elements in array \(A\).
  • The second line of each test case contains \(N\) space-separated integers of array \(A\).

Output format

Print \(T\) lines. For each test case, print \(N\) space-separated integers denoting the length of the valley for each index.

Constraints

\(1 \leq T \leq 20000\)

\(1 \leq N \leq 500000\)

\(1 \leq A_i \leq 10^9\)

Sum of \(N\) over all test cases does not exceed 1000000

 

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:30
3 votes
Tags:
AlgorithmsDynamic ProgrammingDynamic programmingEasy
Points:30
10 votes
Tags:
Basic ProgrammingDynamic ProgrammingAlgorithmsIntroduction to Dynamic Programming 1ImplementationBasics of Implementation
Points:30
10 votes
Tags:
ApprovedData StructuresDynamic ProgrammingEasyReadyRecruitapproved