LeetCode 3269: Constructing Two Increasing Arrays
Problem Description
Explanation:
Given a positive integer n, construct two arrays a and b such that:
- The length of both arrays is n.
- Both arrays a and b are strictly increasing (i.e., a[i] < a[i + 1] and b[i] < b[i + 1] for all valid i).
- The sum of a and b is the maximum possible.
To achieve this, we can construct the arrays a and b in such a way that they are mirror images of each other. We can start with the maximum possible value for a[0] and b[0]. Then, we can iteratively decrease the values for a[i] and b[i] while increasing the values for a[i+1] and b[i+1]. This way, we can ensure that both arrays are strictly increasing and their sum is maximum.
:
Solutions
class Solution {
public int[][] constructDistancedSequence(int n) {
int[] result = new int[2 * n - 1];
boolean[] visited = new boolean[n + 1];
backtrack(result, visited, 0);
int[][] res = new int[2][n];
for (int i = 0; i < 2 * n - 1; i++) {
res[i / n][i % n] = result[i];
}
return res;
}
private boolean backtrack(int[] result, boolean[] visited, int index) {
if (index == result.length) {
return true;
}
if (result[index] != 0) {
return backtrack(result, visited, index + 1);
}
for (int i = visited.length - 1; i > 0; i--) {
if (visited[i]) continue;
if (i == 1) {
result[index] = i;
visited[i] = true;
if (backtrack(result, visited, index + 1)) {
return true;
}
result[index] = 0;
visited[i] = false;
} else if (index + i < result.length && result[index + i] == 0) {
result[index] = result[index + i] = i;
visited[i] = true;
if (backtrack(result, visited, index + 1)) {
return true;
}
result[index] = result[index + i] = 0;
visited[i] = false;
}
}
return false;
}
}
Loading editor...