You are given an array arr of size n . . The array consists of only positive
Fantastic news! We've Found the answer you've been seeking!
Question:
You are given an array arr of size n. The array consists of only positive integers. Your task is to find the maximum difference from each index. Here, the Maximum difference is calculated as the absolute difference between the next greater element(if it exists) on the right side and the maximum element on the right side.
Note:
If there is no next greater element at any index, return 0.
Constraints:
1<= n <=100000
1<= arr[i]<=100000
Input Format:
The first line contains a single integer n
The second line contains n space−separated Integers denoting the array arr.
Output Format:
Print the integer, i.e., maximum difference.
Sample Testcase #0:
Testcase Input:
4
4123
Testcase output:
1
Explanation:
For each Index:
index 0: no greater element than 4 is present.
Index 1: next greater=2 and maximum=3, Hence 3−2=1,
Index 2: next greater=3 and maximum=3. Hence 3−3−0.
Index 3: no greater element than 3 Is present.
Hence, 1 Is printed.
Sample Testcase #1:
Testcase Input:
4
4321
Testcase Output:
0
explaination:
For each Index:
index 0: no greater element than 4 is present.
index 1: no greater element than 3 is present.
Index 2: no greater element than 2 Is present.
Index 3: no greater element than 1 is present.
Hence, 0 is printed.
Write code in cpp.
Related Book For
Artificial Intelligence A Modern Approach
ISBN: 9780134610993
4th Edition
Authors: Stuart Russell, Peter Norvig
Posted Date: