Maximum of Absolute Value Expression LeetCode solution in Java

1
class Solution {
2
public int maxAbsValExpr(int[] arr1, int[] arr2) {
3

4
// 1. remove the modulas -
5
// i & j are interchangable because they are inside the modulas
6
// A[i] - A[j] + B[i] -B[j] + i-j
7
// A[i] + B[i] + i - B[j] - A[j] - j
8
// (A[i] + B[i] + i) ->X
9
// (B[j] - A[j] - j) -> y
10
// X - Y;
11
// to get max value X should be max & Y should min
12

13
// Possible cases (Since both arrays have same number of indexes, we can use single for loop & i
14
// as index)
15
// A[i] + B[i] + i ->1
16
// A[i] - B[i] + i ->2
17
// A[i] + B[i] - i ->3
18
// A[i] - B[i] - i ->4
19

20
// Find out max of all response
21

22
int arrayLength = arr1.length;
23
int v1[] = new int[arrayLength];
24
int v2[] = new int[arrayLength];
25
int v3[] = new int[arrayLength];
26
int v4[] = new int[arrayLength];
27
int res = 0;
28
for (int i = 0; i < arrayLength; i++) {
29
v1[i] = i + arr1[i] + arr2[i];
30
v2[i] = i + arr1[i] - arr2[i];
31
v3[i] = i - arr1[i] + arr2[i];
32
v4[i] = i - arr1[i] - arr2[i];
33
}
34
res = Math.max(res, Arrays.stream(v1).max().getAsInt() - Arrays.stream(v1).min().getAsInt());
35
res = Math.max(res, Arrays.stream(v2).max().getAsInt() - Arrays.stream(v2).min().getAsInt());
36
res = Math.max(res, Arrays.stream(v3).max().getAsInt() - Arrays.stream(v3).min().getAsInt());
37
res = Math.max(res, Arrays.stream(v4).max().getAsInt() - Arrays.stream(v4).min().getAsInt());
38
return res;
39
}
40
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0