Tuesday, February 5, 2019
659. Split Array into Consecutive Subsequences
Greedily append the element to previous sequences
Always try to append
Only create a single sequence if we are not able to append
class Solution {
public boolean isPossible(int[] nums) {
// For every distinct number, we keep track of then consective sequence end with num
// whose length are 1 2 3
int prev = Integer.MIN_VALUE, p1 = 0, p2 = 0, p3 = 0;
for (int i = 0; i < nums.length; i++) {
int curr = nums[i];
int c1 = 0, c2 = 0, c3 = 0;
int count = 1;
// accumulate numbers with same value as curr
while (i < nums.length - 1 && nums[i + 1] == curr) {
count++;
i++;
}
// cannot append to previous number
if (curr != prev + 1) {
if (p1 != 0 || p2 != 0) return false;
c1 = count;
} else { // append to p1 first
if (count < p1 + p2) return false;
c2 = p1;
c3 = p2 + Math.min(p3, count - (p1 + p2));
c1 = Math.max(0, count - (p1 + p2 + p3));
}
prev = curr;
p1 = c1;
p2 = c2;
p3 = c3;
}
return p1 == 0 && p2 == 0;
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment