Previous Next
0 / 21
Module DEMO-32-106DEMO-C-32

Maximum Difference

DEMO-C-32 • Programming in C

Browser-only practice

Problem Statement

You are given an array of integers. Your task is to find the maximum value of: arr[j] - arr[i] where j > i (the larger element must come after the smaller element in the array) In other words: choose two positions in the array where the second number comes later, and compute the difference. Output the largest difference you can get.

Example

Input:

5

7 1 5 3 6

Output:

5

(6 - 1 = 5)

Constraints

n <= 100

Input Format

First line: an integer n (number of elements)

Second line: n integers (the array)

Output Format

Print one integer: the maximum difference arr[j]−arr[i] or any j>i


Sample Testcases

Submit runs every public testcase in this browser. Results and code never leave this device.

Sample #1
Public sample
5
2 3 10 6 4
8
Max diff 10-2.
Sample #2
Public sample
5
10 8 6 4 2
-2
Descending. 8-10 = -2 best we can do (closest neighbors).
Sample #3
Public sample
5
7 9 5 6 3
2
9-7=2. 6-5=1.
Sample #4
Public sample
6
1 5 3 9 2 8
8
9-1=8, maximum difference in the array.
Sample #5
Public sample
1
42
0
Single element, difference with itself is 0.

Web terminal

C, C++, Java, and Python run locally in a browser VM. No worker or visualizer is used.

Saved in this browser
Editor settings