forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_2091.java
60 lines (59 loc) · 2.07 KB
/
_2091.java
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
package com.fishercoder.solutions;
public class _2091 {
public static class Solution1 {
public int minimumDeletions(int[] nums) {
int minIndex = 0;
int maxIndex = 0;
int min = nums[0];
int max = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] > max) {
max = nums[i];
maxIndex = i;
}
if (nums[i] < min) {
min = nums[i];
minIndex = i;
}
}
int minDeletions = 0;
if (nums.length == 1) {
return 1;
}
int len = nums.length - 1;
int firstIndex = maxIndex > minIndex ? minIndex : maxIndex;
int secondIndex = maxIndex == firstIndex ? minIndex : maxIndex;
int firstDistance = firstIndex;
int lastDistance = len - secondIndex;
int betweenDistance = secondIndex - firstIndex;
if (firstDistance < lastDistance) {
minDeletions += firstDistance;
minDeletions++;
if (betweenDistance == 1 || lastDistance == 0) {
minDeletions++;
return minDeletions;
}
if (betweenDistance <= lastDistance) {
minDeletions += betweenDistance;
} else {
minDeletions += lastDistance;
minDeletions++;
}
} else {
minDeletions += lastDistance;
minDeletions++;
if (betweenDistance == 1 || firstDistance == 0) {
minDeletions++;
return minDeletions;
}
if (betweenDistance <= firstDistance) {
minDeletions += betweenDistance;
} else {
minDeletions += firstDistance;
minDeletions++;
}
}
return minDeletions;
}
}
}