forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPartitionArrayintoDisjointIntervals.java
More file actions
45 lines (38 loc) · 1005 Bytes
/
PartitionArrayintoDisjointIntervals.java
File metadata and controls
45 lines (38 loc) · 1005 Bytes
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
class Solution {
// TC : O(n)
// SC : O(n)
public int partitionDisjoint(int[] nums) {
int[] lmax = new int[nums.length];
int[] rmin = new int[nums.length];
int max = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
max = Math.max(max, nums[i]);
lmax[i] = max;
}
int min = Integer.MAX_VALUE;
for (int i = nums.length - 1; i >= 0; i--) {
min = Math.min(min, nums[i]);
rmin[i] = min;
}
for (int i = 1; i < nums.length; i++) {
if (lmax[i - 1] <= rmin[i])
return i;
}
return nums.length;
}
// TC : O(n)
// SC : O(1)
public int partitionDisjoint(int[] nums) {
int maxUntilI = nums[0];
int maxInleftPartition = nums[0];
int partitionId = 0;
for (int i = 1; i < nums.length; i++) {
maxUntilI = Math.max(maxUntilI, nums[i]);
if (nums[i] < maxInleftPartition) {
maxInleftPartition = maxUntilI;
partitionId = i;
}
}
return partitionId + 1;
}
}