2025-02-16 Daily Challenge
Today I have done leetcode's February LeetCoding Challenge with cpp
.
February LeetCoding Challenge 16
Description
Construct the Lexicographically Largest Valid Sequence
Given an integer n
, find a sequence that satisfies all of the following:
- The integer
1
occurs once in the sequence. - Each integer between
2
andn
occurs twice in the sequence. - For every integer
i
between2
andn
, the distance between the two occurrences ofi
is exactlyi
.
The distance between two numbers on the sequence, a[i]
and a[j]
, is the absolute difference of their indices, |j - i|
.
Return the lexicographically largest sequence. It is guaranteed that under the given constraints, there is always a solution.
A sequence a
is lexicographically larger than a sequence b
(of the same length) if in the first position where a
and b
differ, sequence a
has a number greater than the corresponding number in b
. For example, [0,1,9,0]
is lexicographically larger than [0,1,5,6]
because the first position they differ is at the third number, and 9
is greater than 5
.
Example 1:
Input: n = 3 Output: [3,1,2,3,2] Explanation: [2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence.
Example 2:
Input: n = 5 Output: [5,3,1,4,3,5,2,4,2]
Constraints:
1 <= n <= 20
Solution
class Solution {
vector<bool> vis;
vector<int> answer;
int n;
bool solve(int index) {
if(index == 2 * n - 1) return true;
// cout << "#" << answer << endl;
if(answer[index]) return solve(index + 1);
for(int i = min(n, 2 * n - 2 - index); i > 1 ; --i) {
// cout << index << ' ' << i << endl;
if(vis[i]) continue;
// cout << "???" << endl;
if(i != 1 && answer[i + index]) continue;
// cout << "????" << endl;
answer[index] = i;
answer[index + i] = i;
vis[i] = true;
if(solve(index + 1)) return true;
answer[index] = 0;
answer[index + i] = 0;
vis[i] = false;
}
if(!vis[1]) {
answer[index] = 1;
vis[1] = true;
if(solve(index + 1)) return true;
vis[1] = false;
answer[index] = 0;
}
return false;
}
public:
vector<int> constructDistancedSequence(int n) {
this->n = n;
vis.resize(n + 1);
answer.resize(n * 2 - 1);
solve(0);
return answer;
}
};
// Accepted
// 20/20 cases passed (0 ms)
// Your runtime beats 100 % of cpp submissions
// Your memory usage beats 36.8 % of cpp submissions (8.6 MB)