forked from Mugdha-Hazra/PrepBytes-questions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Maximum Difference.cpp
68 lines (56 loc) · 1.15 KB
/
Maximum Difference.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Efficient CPP program to find maximum value
// of |arr[i] - arr[j]| + |i - j|
#include <bits/stdc++.h>
using namespace std;
// Return maximum |arr[i] - arr[j]| + |i - j|
int findValue(int arr[], int n)
{
int a[n], b[n], tmp;
// Calculating first_array and second_array
for (int i = 0; i < n; i++) {
a[i] = (arr[i] + i);
b[i] = (arr[i] - i);
}
int x = a[0], y = a[0];
// Finding maximum and minimum value in
// first_array
for (int i = 0; i < n; i++) {
if (a[i] > x)
x = a[i];
if (a[i] < y)
y = a[i];
}
// Storing the difference between maximum and
// minimum value in first_array
int ans1 = (x - y);
x = b[0];
y = b[0];
// Finding maximum and minimum value in
// second_array
for (int i = 0; i < n; i++) {
if (b[i] > x)
x = b[i];
if (b[i] < y)
y = b[i];
}
// Storing the difference between maximum and
// minimum value in second_array
int ans2 = (x - y);
return max(ans1, ans2);
}
// Driven Program
int main()
{ int t;
cin>>t;
while(t>0)
{
int arr[100000000];
int n ,i;
cin>>n;
for(i=0;i<n;i++)
{cin>>arr[i];}
cout << findValue(arr, n) << endl;
t--;
}
return 0;
}