Question
Leetcode - 面试题 17.08. Circus Tower LCCI
Train of thought
Sorting heights to be ascending order and weights to be descending order. dp[i] = j represents person[i] as the bottom of tower, the tower height is amount of j, to calculate the dp[i] we find the maximum of dp[0 ~ (i-1)] what the person[0 ~ (i-1)] shorter and lighter than person[i], increase it of one, it’s the dp[i] result.
class Solution {
public int bestSeqAtIndex(int[] height, int[] weight) {
int[][] persons = new int[height.length][2];
for (int i = 0; i < height.length; i++) {
persons[i][0] = height[i];
persons[i][1] = weight[i];
}
Arrays.sort(persons, (a, b) -> {
if (a[0] == b[0]) {
return b[1] - a[1];
}
return a[0] - b[0];
});
int[] dp = new int[persons.length];
Arrays.fill(dp, 1);
int max = 1;
for (int i = 1; i < persons.length; i++) {
for (int j = i - 1; j >= 0; j--) {
if (persons[j][1] < persons[i][1]) {
if (dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
}
}
}
if (dp[i] > max) {
max = dp[i];
}
}
return max;
}
}
Optimize
We can optimize the follow code, make it time complexity from O(n) to O(logn):
for (int j = i - 1; j >= 0; j--) {
if (persons[j][1] < persons[i][1]) {
if (dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
}
}
}
if (dp[i] > max) {
max = dp[i];
}
//-------------------- TO BE ------------------
left = 0; right = len;
while (left < right) {
mid = (left + right) / 2;
if (top[mid] > persons[i][1]) {
right = mid;
}
else if (top[mid] < persons[i][1]) {
left = mid + 1;
}
else {
right = mid;
}
}
if (left == len) {
len++;
}
top[left] = persons[i][1];
Following is the complete code
class Solution {
public int bestSeqAtIndex(int[] height, int[] weight) {
int[][] persons = new int[height.length][2];
for (int i = 0; i < height.length; i++) {
persons[i][0] = height[i];
persons[i][1] = weight[i];
}
Arrays.sort(persons, (a, b) -> {
if (a[0] == b[0]) {
// using descending order to avoid choice twice person of the weights are equals,
// the principle is because of we choice the continuous top is ascending order
// and the heap is descending order, it can covered the ahead
return b[1] - a[1];
}
return a[0] - b[0];
});
int[] top = new int[persons.length];
int len = 0, left, right, mid;
for (int i = 0; i < persons.length; i++) {
left = 0; right = len;
while (left < right) {
mid = (left + right) / 2;
if (top[mid] > persons[i][1]) {
right = mid;
}
else if (top[mid] < persons[i][1]) {
left = mid + 1;
}
else {
right = mid;
}
}
if (left == len) {
len++;
}
top[left] = persons[i][1];
}
return len;
}
}