-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNonDecreasingArray.java
73 lines (64 loc) · 1.45 KB
/
NonDecreasingArray.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
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.leetcode.algorithms.easy.array;
import java.util.Scanner;
import com.leetcode.util.InputUtil;
public class NonDecreasingArray {
public static void main(String...strings) {
// Input
Scanner scanner = new Scanner(System.in);
String[] inputs = InputUtil.inputArr(scanner.next());
int[] nums = InputUtil.integerArr(inputs);
// Check possibility
if(checkPossibility(nums)) {
System.out.println("True");
} else {
System.out.println("False");
}
scanner.close();
}
public static boolean checkPossibility(int[] nums) {
if(nums.length == 0) {
return true;
} else {
if(nums.length == 1) {
return true;
} else {
int countModified = 0;
for(int i = 0; i < nums.length; i++) {
if(i == 0) {
if(nums[i] > nums[i + 1]) {
if(countModified > 0) {
return false;
} else {
nums[i] = nums[i + 1];
++countModified;
}
}
} else if(i == nums.length - 1) {
if(nums[i - 1] > nums[i]) {
if(countModified > 0) {
return false;
} else {
nums[i - 1] = nums[i];
++countModified;
}
}
} else {
if(nums[i] > nums[i + 1]) {
if(countModified > 0) {
return false;
} else {
if(nums[i - 1] > nums[i + 1]) {
nums[i + 1] = nums[i];
} else {
nums[i] = nums[i - 1];
}
++countModified;
}
}
}
}
return true;
}
}
}
}