Answered step by step
Verified Expert Solution
Question
1 Approved Answer
You are given an array arr of size n . . The array consists of only positive integers. Your task is to find the maximum
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.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Here is the C code for the given problem include include include using ...Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started