forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGlobalandLocalInversions.java
53 lines (43 loc) · 1.08 KB
/
GlobalandLocalInversions.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
class Solution {
// TC : O(n)
// SC : O(1)
public boolean isIdealPermutation(int[] A) {
int cMax = A[0];
for(int i=0;i<A.length-2;i++){
cMax = Math.max(cMax, A[i]);
if(cMax>A[i+2]){
return false;
}
}
return true;
}
// TC : O(n2) passed
public boolean isIdealPermutation(int[] A) {
for(int i=0;i<A.length;i++){
for(int j=i+2;j<A.length;j++){
if(A[i]>A[j]){
return false;
}
}
}
return true;
}
// O(n2) Causing TLE
public boolean isIdealPermutation(int[] A) {
int local = 0;
for(int i=0;i<A.length-1;i++){
if(A[i]>A[i+1]){
local++;
}
}
int global = 0;
for(int i=0;i<A.length;i++){
for(int j=i+1;j<A.length;j++){
if(A[i]>A[j]){
global++;
}
}
}
return local ==global;
}
}