init: init commit
All checks were successful
Build and Deploy Quartz / build-and-deploy (push) Has been skipped

This commit is contained in:
2026-01-01 14:16:34 +08:00
commit 4a5acab07d
216 changed files with 40383 additions and 0 deletions

View File

@@ -0,0 +1,235 @@
---
date: 2025-12-26
tags:
- DynamicProgramming
- Classic
---
> [!note]
>
> This note is an extension to [[Maximum Task Value]], please read that first
Now consider what will happen if we **add limit to the task count we could choose in total**, say $2$. That means we could choose at most $2$ different tasks, then in this case, what's the maximum profit?
You could also checkout the related Leetcode question [Two Best Non-overlapping Events](https://leetcode.com/problems/two-best-non-overlapping-events)
# Analysis
We could consider this #DynamicProgramming question with two constrain:
- Constrain 1: Task time period could not overlap
- Constrain 2: Task count $\le 2$
In this case, the original transfer equation becomes:
```cpp
// not choose
solutions[layer][i] = solutions[layer][i - 1]
// choosed
solutions[layer][i] = Ti.value + solutions[layer - 1][Ti.start - 1]
```
## Layer 1 Solution Calculation
We already know **for layer $0$, the solution is always $0$.** Consider that is we are only allow to **choose at most $0$ items**, then the best maximum **sum of value we got should always be zero**.
Then based on transfer equation above:
```cpp
// not choose
solutions[1][i] = solutions[1][i - 1]
// choosed
solutions[layer][i] = Ti.value
```
It's easy to proof that such transfer equation is actually mean to always choose the single one task with maximum value in time period `[0, i]`. This is intuitive, since when only one task it allowed, we don't need to think things like time-overlapping, we just always choose one task that with maximum value.
## Code Implementation
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <format>
using LL = long long;
using std::cout, std::endl;
using std::vector;
const bool debug = false;
// task struct
struct Task
{
int start;
int end;
int value;
};
// < override for task struct
bool operator<(const Task &ta, const Task &tb)
{
return ta.end < tb.end;
}
std::ostream &operator<<(std::ostream &os, const Task &t)
{
os << std::format("<Task start={} end={} value={}>", t.start, t.end, t.value);
return os;
}
struct SolutionData
{
int time;
int value;
SolutionData() : time(0), value(0) {}
SolutionData(int time, int value) : time(time), value(value) {}
};
bool operator<(const SolutionData &sa, const SolutionData &sb)
{
return sa.time < sb.time;
}
std::ostream &operator<<(std::ostream &os, const SolutionData &so)
{
os << std::format("[time={}, value={}]", so.time, so.value);
return os;
}
const int MAX_SIZE = 50010;
// global variables
vector<Task> tasks;
int size = 0;
void initTasks()
{
tasks.clear();
tasks.reserve(MAX_SIZE);
}
using SolutionVec = vector<SolutionData>;
// usage: Solution solutions[layer][time];
SolutionVec solutions[3];
SolutionData &getLastSolution(int layer)
{
return solutions[layer].back();
}
int getSolutionValue(int layer, int time)
{
time = std::max(time, 0);
const SolutionData &lastSolution = getLastSolution(layer);
// target time > maximum solution time
// don't need binary search anymore, the last solution is the maximum possible solution
// at this point (this assumption relies on the iteration order of low endTime to high endTime)
if (time > lastSolution.time)
{
return lastSolution.value;
}
else
{
// search on specified layer
auto &curLayerSolution = solutions[layer];
auto res = std::lower_bound(curLayerSolution.begin(), curLayerSolution.end(), SolutionData(time, 0));
if ((*res).time > time)
{
--res;
}
return (*res).value;
}
}
// set new solution in solutions array with basic checking
void setSolution(int layer, const SolutionData &newSolution)
{
SolutionData &lastSolution = getLastSolution(layer);
if (newSolution.time < lastSolution.time)
{
cout << "[Warning] Should not update solution time earlier than previous" << endl;
return;
}
if (newSolution.value <= lastSolution.value)
{
cout << "[Warning] Should not update solution value smaller than previous" << endl;
return;
}
if (newSolution.time == lastSolution.time)
{
lastSolution.value = newSolution.value;
}
else
{
solutions[layer].push_back(newSolution);
}
}
// use data in tasks array to initial layer 0 and layer 1 solutions
// also add initial (time=0, value=0) solution to layer 2
// require task to be sorted by endTime
void initSolutions()
{
auto &s = solutions;
for (int l = 0; l < 3; ++l)
{
s[l].clear();
s[l].emplace_back(SolutionData());
}
// layer 1
for (const auto &t : tasks)
{
SolutionData &last = getLastSolution(1);
if (t.value > last.value)
{
setSolution(1, SolutionData(t.end, t.value));
}
}
}
void initLayer2Solution()
{
int notChoose, choose;
for (const auto &curTask : tasks)
{
notChoose = getLastSolution(2).value;
choose = curTask.value + getSolutionValue(1, curTask.start - 1);
if (choose > notChoose)
{
setSolution(2, SolutionData(curTask.end, choose));
}
}
}
class Solution
{
public:
int maxTwoEvents(vector<vector<int>> &events)
{
// init and format tasks
initTasks();
for (const auto &taskData : events)
{
tasks.emplace_back(Task(taskData[0], taskData[1], taskData[2]));
}
// sort tasks
std::sort(tasks.begin(), tasks.end());
// init solutions
initSolutions();
initLayer2Solution();
return getLastSolution(2).value;
}
};
```

View File

@@ -0,0 +1,270 @@
---
date: 2025-12-26
tags:
- Classic
- DynamicProgramming
---
# Question Description
Consider we are given a set of tasks, with `startTime`, `endTime` and `value`. For certain task, `startTime <= endTime`, indicates task time range `[startTime, endTime]`
Now we need to **choose as many not intersected tasks as possible** to **maximize the total `value` of chosen tasks**. *(Note that `endTime` is considered in the time range, so `[1, 2]` and `[2, 3]` is intersected)*
You could also checkout the related Leetcode question [Maximum Profit In Job Scheduling](https://leetcode.com/problems/maximum-profit-in-job-scheduling/)
# Analysis
My first thought is to use #DynamicProgramming to solve this question.
Consider we've **already known the best solution when only considering time period `[t + 1, infty]`**, that is, we already known `solution[k]` in which $k \in [t+1, +\infty)$.
And now, we consider task `Ti`.
> [!note]
>
> `solution[t]` here means the maximum sum of `value` we choose achieve by ONLY selecting tasks that `startTime` and `endTime` falls into the range `[t, infty]`.
>
> `infty` here refers to $+\infty$.
## Case1: Choose task `Ti`
In this case, the task we could choose is:
- Task `Ti`
- All the other tasks that need to be chosen to make range `[Ti.endTime + 1, infty]` reach's the maximum value `solution[Ti.endTime + 1]`
the new value sum will be:
```cpp
solution[i] = Ti.value + solution[Ti.endTime + 1]
```
## Case2: Not Choose task `Ti`
In this case, since nothing changed compared to previous state, we have:
```cpp
solution[i] = solution[i + 1]
```
## Sort Task By Time
Notice above, we have one of the state transfer formula:
```cpp
solution[i] = solution[i + 1]
```
To ensure `solution[i + 1]` is the best solution we could found, when processing `Ti`, all task start later than `i` must be already considered.
In order to satisfy this, we could sort task by it's `startTime` and iterate from the one with largest `startTime` to the one with smallest `startTime`. By doing this, when processing `Ti` with start time `t`, all tasks that starts later then `t` will be iterated before, thus, already considered.
> [!note]
>
> The state transfer equation and the iteration above use the direction from the largest `startTime` to smallest. However, it's easy to proof that the **iteration could goes from the smallest to the largest as well**.
>
> In this case, we need to use sort criteria `endTime` instead of `startTime` to sort the array, and the state transfer equation should also be modified:
>
> ```cpp
> solution[i] = Ti.value + solution[Ti.startTime - 1];
> ```
>
> or
>
> ```cpp
> solution[i] = solution[i - 1];
> ```
# Code Implementation
[Leetcode Question Link](https://leetcode.com/problems/maximum-profit-in-job-scheduling/)
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <format>
using LL = long long;
using std::cout, std::endl;
using std::vector;
const bool debug = false;
// task struct
struct Task
{
int start;
int end;
int value;
};
// < override for task struct
bool operator<(const Task &ta, const Task &tb)
{
return ta.end < tb.end;
}
std::ostream &operator<<(std::ostream &os, const Task &t)
{
os << std::format("<Task start={} end={} value={}>", t.start, t.end, t.value);
return os;
}
struct SolutionData
{
int time;
int value;
SolutionData() : time(0), value(0) {}
SolutionData(int time, int value) : time(time), value(value) {}
};
bool operator<(const SolutionData &sa, const SolutionData &sb)
{
return sa.time < sb.time;
}
std::ostream &operator<<(std::ostream &os, const SolutionData &so)
{
os << std::format("[time={}, value={}]", so.time, so.value);
return os;
}
const int MAX_SIZE = 50010;
// global variables
Task tasks[MAX_SIZE];
int size = 0;
// store the solutions
int solutionSize = 0;
SolutionData solutions[MAX_SIZE];
SolutionData &getLastSolution()
{
return solutions[solutionSize - 1];
}
int getSolutionValue(int time)
{
const SolutionData &lastSolution = getLastSolution();
if (time < 0)
time = 0;
const SolutionData *sd;
if (time > lastSolution.time)
{
sd = &lastSolution;
if (debug)
{
cout << "use last solution as answwer: " << (*sd) << endl;
}
}
else
{
if (debug)
{
cout << "solutionSize: " << solutionSize << endl;
cout << "lower bound serach range: " << *solutions << " to " << *(solutions + solutionSize) << endl;
}
sd = std::lower_bound(solutions, solutions + solutionSize, SolutionData(time, 0));
if (debug)
{
cout << "lower bound got: " << (*sd) << endl;
}
if (sd->time > time)
sd -= 1;
if (debug)
{
cout << "use lower bound as answwer: " << (*sd) << endl;
}
}
if (debug)
{
cout << "solution time=" << time << " is " << (*sd) << endl;
}
return sd->value;
}
// set new solution in solutions array with basic checking
void setSolution(const SolutionData &newSolution)
{
if (debug)
{
cout << "got new solution update request: " << newSolution << endl;
}
SolutionData &lastSolution = getLastSolution();
if (newSolution.time < lastSolution.time)
{
cout << "[Warning] Should not update solution time earlier than previous" << endl;
return;
}
if (newSolution.value <= lastSolution.value)
{
cout << "[Warning] Should not update solution value smaller than previous" << endl;
return;
}
if (newSolution.time == lastSolution.time)
{
lastSolution.value = newSolution.value;
}
else
{
solutions[solutionSize++] = newSolution;
}
if (debug)
{
cout << "solution updated: " << getLastSolution() << endl;
}
return;
}
class Solution
{
public:
int jobScheduling(vector<int> &startTime, vector<int> &endTime, vector<int> &profit)
{
solutionSize = 0;
int size = profit.size();
for (int i = 0; i < size; ++i)
{
// startTime + 1 to match time-slot indexing instead of time point indexing
// in time-slot indexing, endTime is also considered into the time range,
// E.g. [1, 2] and [2, 3] are intersected
tasks[i] = Task(startTime[i] + 1, endTime[i], profit[i]);
}
// sort task by `start`
std::sort(tasks, tasks + size);
// init solutions
solutions[0] = SolutionData();
solutionSize += 1;
// dp to get solution
for (int i = 0; i < size; ++i)
{
Task &curTask = tasks[i];
if (debug)
{
cout << "currently processing: " << curTask << endl;
}
int valueNotChoosed = getLastSolution().value;
int valueChoosed = getSolutionValue(curTask.start - 1) + curTask.value;
if (valueChoosed > valueNotChoosed)
{
setSolution(SolutionData(curTask.end, valueChoosed));
}
}
return getLastSolution().value;
}
};
```

View File

@@ -0,0 +1,402 @@
---
tags:
- BinarySearch
date: 2025-12-27
---
# Definitions
## Non-Decreasing
Non-decreasing array is an array that satisfies:
```cpp
arr[i + 1] >= arr[i]
```
For example:
```cpp
int arr[] = {1, 1, 1, 3, 3, 5, 6, 8, 8}
```
## Breakpoint
Here, in this article, we define an `idx` as a breakpoint if it satisfies:
```cpp
(idx == 0 || idx[idx] > idx[idx - 1])
```
![[251227_breakpoint.jpg]]
## Breakpoint Info
Breakpoint Info contains the breakpoint and the value of the array element at that breakpoint:
```cpp
struct BreakpointInfo {
int idx;
T value;
}
```
# Operations
## Add New Breakpoint
The implementation we gave below only support adding new breakpoint that **not breaking previous info**. Concretely, that is:
- The `idx` must be larger or equal than any before
- The `value` must be larger then any before
## Get Value At Index
### Question Definition
This operation should return the actual value at an index based on that "compressed" breakpoint info. Given an `targetIdx`.
Based on the definition of breakpoint, we know our goal is actually to **find the last element `elem` that satisfies**:
```cpp
elem.idx <= targetIdx
```
### Special Case
First of all, in order to promise binary search `std::lower_bound` return a point to a valid info, we need to promise `idx` in a valid range, that is:
$$
\text{idx} \in [0, \text{maxIdx}]
$$
- When `idx < 0`, we modified it to `0`
- When `idx > maxIdx`, then the last element is what we want, return directly
### Binary Searching
In my implementation, I use the `std::lower_bound()` to find the element position `res`.
Lower bound function **returns the first position where we could insert target without breaking the order of sequence**. In a more understandable way, if we provide `targetIdx`, it will return the position of the first element that satisfies:
```cpp
(*it).idx >= target.idx;
```
However, based on our definition of `NonDecreasingArray`, we actually want to find the last element that:
```cpp
(*it).idx <= target.idx;
```
So we need an extra check:
```cpp
if((*it).idx > target.idx)
it--;
```
After this work, `it` now is pointing at the element we want.
# Code Implementation
## Non-Decreasing Array
```cpp
template <typename T>
class NonDecreasingArray
{
private:
using Idx = int;
public:
struct BreakpointInfo
{
Idx idx = 0;
T value = T();
bool operator<(const BreakpointInfo &other) const
{
return idx < other.idx;
}
};
private:
vector<BreakpointInfo> mInfo;
public:
/**
* Initialize array with initial breakpoint info
*/
NonDecreasingArray()
{
mInfo.clear();
mInfo.push_back(BreakpointInfo());
}
/**
* Return the reference of last breakpoint info
*/
BreakpointInfo &getLastBreakpointInfo()
{
return mInfo.back();
}
/**
* Insert a new breakpoint into
*
* Require such breakpoint info to have:
* - larger or equal index than last addition
* - larger or equal value than last addition
*
* Otherwise, the addition opeartion will be ignored
*/
void addNewBreakpoint(Idx idx, const T &value)
{
// normalize idx
idx = std::max(0, idx);
// check if this is a valid new breakpoint info
BreakpointInfo &last = getLastBreakpointInfo();
if (idx < last.idx || value < last.value)
{
cout << "Warning: update ignored";
return;
}
// update value
if (idx == last.idx)
{
last.value = value;
}
else
{
mInfo.emplace_back(BreakpointInfo(idx, value));
}
}
/**
* return the value at target index based on breakpoint info
*/
const T &operator[](Idx targetIdx)
{
targetIdx = std::max(0, targetIdx);
BreakpointInfo &last = getLastBreakpointInfo();
if (targetIdx > last.idx)
{
return last.value;
}
BreakpointInfo target = BreakpointInfo(targetIdx, T());
auto res = std::lower_bound(mInfo.begin(), mInfo.end(), target);
const BreakpointInfo &resInfo = *res;
if (resInfo.idx > targetIdx)
{
res--;
}
return (*res).value;
}
};
```
## Usage In Real Question
Actually, we could use this custom data structure to store the DP array used in [[Maximum Task Value]] questions, checkout the code below or on [Leetcode Submission page](https://leetcode.com/problems/two-best-non-overlapping-events/submissions/1866290240)
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <format>
using LL = long long;
using std::cout, std::endl;
using std::vector;
const bool debug = true;
template <typename T>
class NonDecreasingArray
{
private:
using Idx = int;
public:
struct BreakpointInfo
{
Idx idx = 0;
T value = T();
bool operator<(const BreakpointInfo &other) const
{
return idx < other.idx;
}
};
private:
vector<BreakpointInfo> mInfo;
public:
/**
* Initialize array with initial breakpoint info
*/
NonDecreasingArray()
{
mInfo.clear();
mInfo.push_back(BreakpointInfo());
}
/**
* Return the reference of last breakpoint info
*/
BreakpointInfo &getLastBreakpointInfo()
{
return mInfo.back();
}
/**
* Insert a new breakpoint into
*
* Require such breakpoint info to have:
* - larger or equal index than last addition
* - larger or equal value than last addition
*
* Otherwise, the addition opeartion will be ignored
*/
void addNewBreakpoint(Idx idx, const T &value)
{
// normalize idx
idx = std::max(0, idx);
// check if this is a valid new breakpoint info
BreakpointInfo &last = getLastBreakpointInfo();
if (idx < last.idx || value < last.value)
{
cout << "Warning: update ignored";
return;
}
// update value
if (idx == last.idx)
{
last.value = value;
}
else
{
mInfo.emplace_back(BreakpointInfo(idx, value));
}
}
/**
* return the value at target index based on breakpoint info
*/
const T &operator[](Idx targetIdx)
{
targetIdx = std::max(0, targetIdx);
BreakpointInfo &last = getLastBreakpointInfo();
if (targetIdx > last.idx)
{
return last.value;
}
BreakpointInfo target = BreakpointInfo(targetIdx, T());
auto res = std::lower_bound(mInfo.begin(), mInfo.end(), target);
const BreakpointInfo &resInfo = *res;
if (resInfo.idx > targetIdx)
{
res--;
}
return (*res).value;
}
};
// task struct
struct Task
{
int start;
int end;
int value;
};
// < override for task struct
bool operator<(const Task &ta, const Task &tb)
{
return ta.end < tb.end;
}
const int MAX_SIZE = 50010;
// global variables
vector<Task> tasks;
int size = 0;
// solution data
NonDecreasingArray<int> solutions[3];
void initTasks()
{
tasks.clear();
tasks.reserve(MAX_SIZE);
}
// use data in tasks array to initial layer 0 and layer 1 solutions
// also add initial (time=0, value=0) solution to layer 2
// require task to be sorted by endTime
void initSolutions()
{
auto &s = solutions;
solutions[1] = NonDecreasingArray<int>();
solutions[2] = NonDecreasingArray<int>();
// layer 1
for (const auto &t : tasks)
{
auto last = solutions[1].getLastBreakpointInfo();
if (t.value > last.value)
{
solutions[1].addNewBreakpoint(t.end, t.value);
}
}
}
void initLayer2Solution()
{
int notChoose, choose;
for (const auto &curTask : tasks)
{
notChoose = solutions[2].getLastBreakpointInfo().value;
choose = curTask.value + solutions[1][curTask.start - 1];
if (choose > notChoose)
{
solutions[2].addNewBreakpoint(curTask.end, choose);
}
}
}
class Solution
{
public:
int maxTwoEvents(vector<vector<int>> &events)
{
// init and format tasks
initTasks();
for (const auto &taskData : events)
{
tasks.emplace_back(Task(taskData[0], taskData[1], taskData[2]));
}
// sort tasks
std::sort(tasks.begin(), tasks.end());
// init solutions
initSolutions();
initLayer2Solution();
return solutions[2].getLastBreakpointInfo().value;
}
};
```

Binary file not shown.

View File

@@ -0,0 +1,5 @@
---
title: Classic Questions
date: 2025-12-26
---
Some of the classic question templates in coding questions.

View File

@@ -0,0 +1,19 @@
filters:
and:
- file.inFolder("Leetcode Questions")
- file.ext == "md"
views:
- type: table
name: Table
order:
- file.name
- title
- date
- file.tags
- file.mtime
sort:
- property: date
direction: DESC
columnSize:
note.title: 162
file.tags: 256

View File

@@ -0,0 +1,126 @@
---
tags:
- Greedy
- Heap
date: 2025-12-22
---
[Leetcode Question Link](https://leetcode.com/problems/maximize-happiness-of-selected-children/?envType=daily-question&envId=2025-12-25)
For the convenience, we use $a[i]$ to denote $\text{happiness}[i]$ in article below.
# Analysis
## Gain From One Child
Consider if we chose children $i$ at time $t, \;t \in [0, k)$, what could we add to the final sum?
If not considering our choice, the lost of the happiness $L$ should be:
$$
L(i) = min(a[i], k)
$$
- If $a[i] \le k$, this means the $a[i]$ will goes to $0$ before the procedure finished, so the maximum decrease of the value is from $a[i]$ to $0$, that is, $L = a[i]$
- If $a[i] > k$, that means $a[i]$ never reach $0$, the decrease value is exactly the round $k$. So we have $L = k$.
Now take our choice operation into consideration. If we chose a child at time $t$, then the actual lost of happiness of this child should be:
$$
L_{A}(i, t) = min(L(i), t)
$$
- If $t < L$, means we chose this child while it's decreasing, this means if we chose this child, it should be decreasing from time $0$ to time $t$, the actual decrease value $L_{A} = t$.
- If $t > L$, means this child's happiness already stop decreasing, our action of choice actually has no effect, so $L_{A} = L$.
-----
In conclusion, we could know that for any child $i$, if we choice it, the happiness value $H$ we could get will be:
$$
\begin{align}
H(i, t) &= a[i] - L_{A}(i, t) \\[1em]
&= a[i] - min(min(a[i], k), t) \\[1em]
&= a[i] - min(a[i], k, t)
\end{align}
$$
## Choose Child
Based on analysis above, we should be aware that the greedy strategy could be used for this question. That is, **to ensure highest final sum, we should always choose child with largest initial happiness first**.
Consider the formula of $H(i, t)$:
$$
H(i, t) = a[i] - min(a[i], k, t)
$$
If we want to make $H(i, t)$ larger, we need to make $min(a[i], k, t)$ smaller, so we should put larger $a[i]$ with smaller $t$. And that, in this problem, means choose child with larger happiness sooner.
# Code
```cpp
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
using std::priority_queue;
using std::vector;
bool debug = false;
struct MyMinHeap : std::priority_queue<int, std::vector<int>, std::greater<int>> {
void reserve(size_t n) { this->c.reserve(n); }
};
class Solution {
public:
long long maximumHappinessSum(vector<int>& happiness, int k) {
// min heap
MyMinHeap maxk;
maxk.reserve(k);
int cur, top;
// initial heap with k elements
for (int i = 0; i < k; ++i) {
maxk.push(happiness[i]);
}
// iterate while update
for (int i = k; i < happiness.size(); ++i) {
cur = happiness[i];
top = maxk.top();
// current elements smaller, just continue
if (cur <= top) {
continue;
}
// update elements
maxk.pop();
maxk.push(cur);
}
// at this point, all max-k elements are in the min heap
long long answer = 0;
int chooseTime, lost;
for (chooseTime = k - 1; chooseTime >= 0; --chooseTime) {
// get top element
cur = maxk.top();
maxk.pop();
if (debug) {
cout << "choosed: " << cur << endl;
}
// determine the lost of this element
lost = std::min({k, cur, chooseTime});
// update answer
answer += (cur - lost);
}
return answer;
}
};
```

View File

@@ -0,0 +1,347 @@
---
date: 2025-12-29
tags:
- Simulation
- "#Heap"
---
[Leetcode question link](https://leetcode.com/problems/meeting-rooms-iii)
# Analysis
Basically this is just an #Simulation problem.
> [!note]
>
> The most important time complexity optimization is to find out the **unused room management could exploit #Heap data structure**, checkout [[#Room Distribution Order]] for details
## Meeting Distribution Order
Since the `startTime` is promised to be unique, based on the rule, we know that the **distribution should goes from meetings with smaller `startTime` to larger one**. The basic thought is:
1. Sort `meetings`
2. Distribute `meeting` to room, counting usage statistics of each room
3. Output most used room
## Room Distribution Order
Based on the rules, we know that the room being distributed is **always the one with the smallest room number and currently available**. Conclude what operations we need for rooms.
| Operation | Descriptions |
| ---------------- | ----------------------------------------------------------------------------------------------- |
| `use()` | Mark a room used, that room should have the lowest `roomIdx` among all currently available room |
| `unuse(roomIdx)` | Unuse a room by it's index |
Here we introduce two approaches to achieve these.
### Array
We use an array `bool isUsed[N]` to record the status of a room. This require us to iterate the array to find out the lowest unused index, thus has time complexity $O(N)$
### Min Heap
We could find Minimum Heap suit this use case really well. We initial a min heap with all unused room index, and:
- `use()` Remove the index at the heap top
- `unuse()` Insert the index to the heap
By doing this, we could have $O(\log N)$ time complexity, considering $N$ is the number of room.
# Code Implementation
```cpp
#include <iostream>
#include <numeric>
#include <vector>
#include <format>
#include <algorithm>
#include <queue>
using std::cout, std::endl, std::format;
using std::vector, std::priority_queue;
const bool debug = false;
struct TaskInfo
{
unsigned start = 0;
unsigned end = 0;
TaskInfo(const vector<int> &vec) : start(vec[0]), end(vec[1]) {}
bool operator<(const TaskInfo &other)
{
if (start != other.start)
{
return start < other.start;
}
return end < other.end;
}
unsigned duration() const
{
return end - start;
}
void delay(unsigned delta)
{
start += delta;
end += delta;
}
void relocate(unsigned startTime)
{
end = startTime + duration();
start = startTime;
}
};
class MeetingRoomManager
{
private: // private member
vector<unsigned> mUseCount;
unsigned tmpMostUsedCount = 0;
std::priority_queue<unsigned, std::vector<unsigned>, std::greater<unsigned>> tmpUnusedIdxHeap;
public: // public member
// the count of the room
unsigned mCount = 0;
public: // public method
// initialize manager with room count
MeetingRoomManager(int count) : mCount(count)
{
mUseCount = vector<unsigned>(100);
clear(count);
}
/**
* Find a valid room, mark it as used and update the use count.
* Return index of the used room.
*
* Return 100 if room not found.
*/
unsigned use()
{
// room not found
if (tmpUnusedIdxHeap.empty())
{
return 100;
}
// found room with lowest index
unsigned unuse = tmpUnusedIdxHeap.top();
tmpUnusedIdxHeap.pop();
++mUseCount[unuse]; // update use count
// update most use if needed
if (mUseCount[unuse] > tmpMostUsedCount)
{
tmpMostUsedCount = mUseCount[unuse];
}
return unuse; // return room idx
}
/**
* Unuse a room by its index
*/
void unuse(unsigned roomIdx)
{
tmpUnusedIdxHeap.push(roomIdx);
}
unsigned mostUsedIdx()
{
for (int i = 0; i < mCount; ++i)
{
if (mUseCount[i] == tmpMostUsedCount)
{
return i;
}
}
return 0;
}
bool isFull()
{
return tmpUnusedIdxHeap.empty();
}
void clear(unsigned count)
{
// reset mCount
mCount = count;
// clear most use count
tmpMostUsedCount = 0;
// clear use count statistics
std::fill(mUseCount.begin(), mUseCount.end(), false);
// init unuse heap
tmpUnusedIdxHeap = std::priority_queue<unsigned, std::vector<unsigned>, std::greater<unsigned>>();
for (int i = 0; i < mCount; ++i)
{
tmpUnusedIdxHeap.push(i);
}
}
};
class RoomDistributor
{
private: // private classes
struct FutureReleaseInfo
{
unsigned time;
unsigned roomIdx;
bool operator<(const FutureReleaseInfo &other) const
{
if (time != other.time)
{
return time > other.time;
}
return roomIdx > other.roomIdx;
}
};
private: // private members
// manage room usage info
MeetingRoomManager mManager;
// record current timestamp
unsigned mCurTimestamp = 0;
// record when to release room
std::priority_queue<FutureReleaseInfo> mReleaseTimeHeap;
private: // private methods
// release one from heap
// will NOT check empty before action!
void releaseOne()
{
const FutureReleaseInfo &nextReleaseInfo = mReleaseTimeHeap.top();
mManager.unuse(nextReleaseInfo.roomIdx);
mCurTimestamp = std::max({nextReleaseInfo.time, mCurTimestamp});
mReleaseTimeHeap.pop();
}
// release all the room until the given timestamp
void pushTimeTo(unsigned targetTime)
{
// already pushed to a time later then given, nothing to do
if (mCurTimestamp > targetTime)
{
return;
}
// no room is used, just move the time
if (mReleaseTimeHeap.empty())
{
mCurTimestamp = targetTime;
return;
}
// release until target time
while (!mReleaseTimeHeap.empty() && mReleaseTimeHeap.top().time <= targetTime)
{
releaseOne();
}
mCurTimestamp = targetTime;
}
public:
RoomDistributor(unsigned roomCount) : mManager(roomCount) {}
// distribute a meeting task to the room
void distributeTask(const TaskInfo &taskInfo)
{
pushTimeTo(taskInfo.start);
// if room still full, push timestamp until next room release
if (mManager.isFull())
{
releaseOne();
}
// distribute a room
unsigned roomIdx = mManager.use();
// record a new future release
mReleaseTimeHeap.emplace(FutureReleaseInfo(mCurTimestamp + taskInfo.duration(), roomIdx));
}
/**
* Release all item that should be released in the future
*/
void releaseAll()
{
while (!mReleaseTimeHeap.empty())
{
releaseOne();
}
}
unsigned getMostUsedIdx()
{
return mManager.mostUsedIdx();
}
void clear(unsigned count)
{
// reset timestamp
mCurTimestamp = 0;
// clean heap
releaseAll();
// clear mManager
mManager.clear(count);
}
};
// global variables
unsigned roomCount, meetingCount;
RoomDistributor distributor(0);
vector<TaskInfo> tasks;
void initVariables(const vector<vector<int>> &meetings)
{
// init tasks
tasks.clear();
tasks.reserve(meetings.size());
for (const auto &m : meetings)
{
tasks.emplace_back(TaskInfo(m));
}
std::sort(tasks.begin(), tasks.end());
// init distributor
distributor.clear(roomCount);
}
void triggerSimulation()
{
for (const auto &t : tasks)
{
distributor.distributeTask(t);
}
distributor.releaseAll();
}
class Solution
{
public:
int mostBooked(int n, vector<vector<int>> &meetings)
{
roomCount = n;
meetingCount = meetings.size();
initVariables(meetings);
triggerSimulation();
return distributor.getMostUsedIdx();
}
};
```

View File

@@ -0,0 +1,75 @@
---
tags:
- Greedy
- Array
date: 2025-12-26
---
[Leetcode Question Link](https://leetcode.com/problems/minimum-penalty-for-a-shop)
# Analysis
## Offset
The target is to **find the time to achieve the smallest penalty, but not the penalty value itself**. So the concrete value of penalty is not important, we could just focus on **how penalty changes when changing shop closing time**.
Let `offset` be the penalty diff when choosing closing time $i$ and closing time $0$, that is:
$$
\text{offset}(i) = \text{penalty}(i) - \text{penalty}(0)
$$
## Moving Closing Time
Now let's find how $\text{offset}(i)$ changes when $i: 0 \to n$.
---
When $i = 0$, based on definition of offset, we have $\text{offset}(0) = 0$
-----
When we moving closing time $i$ from $k - 1$ to $k$, discuss:
**When at $k-1$ hour, there IS customers arriving.** In this case, before moving closing time, there is an $Y$ in closing time, after moving, the $Y$ has been moved into open time. So $\text{offset}$ actually decrease by $1$ after moving.
**When at $k-1$ hour, there IS NOT customers arriving.** by similar analysis method, we know there is an $N$ moved from closing time to opening time, $\text{offset}$ increase by $1$.
# Code Implementation
```cpp
class Solution {
public:
int bestClosingTime(string customers) {
// init offset
// at time 0, offset = 0
int offset = 0, minOffset = 0;
unsigned minTime = 0;
bool arrived;
int rangeEnd = customers.size() + 1;
for (int i = 1; i < rangeEnd; ++i) {
// check if there is customers arrived at previous time
arrived = (customers[i - 1] == 'Y' ? 1 : 0);
// someone arrived, then moving closing time
// 1 hour later will cause offset decreasing by 1,
// otherwise, offset increasing by 1
if (arrived)
--offset;
else
++offset;
// update minOffset and minTime
if (offset < minOffset) {
minOffset = offset;
minTime = i;
}
}
return minTime;
}
};
```

View File

@@ -0,0 +1,602 @@
---
date: 2025-12-31
tags:
- DFS
- Search
- Cache
---
[Leetcode Question Link](https://leetcode.com/problems/pyramid-transition-matrix/)
# Analyze
## Basic Thought
For each pyramid block, the possible color (represented by one single character) is limited to following:
```
color = A, B, C, D, E, F
```
The intuitive is to use #Search to **iterate through the solution space** *(all possible value of the elements in pyramid)* to find the final answer.
## Searching
### Store Current Search State
The the image shows below, we store the pyramid info info an 2D `char` array:
![[251231_store_search_info.png]]
And define meaning of the value in the elements as follow:
| Value | Description |
| ------- | ---------------- |
| `0` | Not yet searched |
| `[A-F]` | Searching |
| `1` | Searched |
### Search Direction
We search **from right to left, from bottom to top**. More concretely, consider current searching position is `[curR][curC]`, then next search position could be calculated by code below:
```python
def pos_forward(curR, curC):
if(curC > 0):
--curC # one step left
else:
--curR # search the layer above
curC = curR # start from right-most element
```
> [!note]
>
> Please note that all Python code in this post is intended solely to illustrate the logic and should be regarded as pseudocode.
>
> For runnable C++ code, checkout [[#Code Implementation]] sector.
![[251231_search_direction.png]]
### Search Implementation
I decided to use a **non-recursive way** to implement DFS search in the solution space.
The search strategy could be explained by the code below:
```python
def _search():
# global variables
global curR
global curC
# if already found valid answer, or search already finished
# return directly
if found or finished:
return
# search for this position is finished
if currChar == '1':
# if this is the search starting point
# then it means the whole solution space has been searched
if [curR, curC] == [bottom_size - 1, bottom_size - 1]:
finished = True
return
# else, we go one step backward.
#
# setting current position value to '0' is necessary,
# since if not doing so, next time we search this position,
# program will directly skip searching and go backward()
currChar == '0'
pos_backward()
return
# at here, the search of current position must NOT finished
currChar = next_possible_char_for_this_pos()
# this is the last position to search, and we found a valid color
if currChar != '1' and [curR, curC] == [0, 0]:
found = True
return
pos_forward()
def search() -> bool:
while (not finished) and (not found):
_search()
return found
```
In code above:
- `pos_forward() / pos_backward()` modify `curR, curC` to point to next / previous search position
- `next_possible_char_for_this_pos()` will return next valid color character for current position based on allowed patterns and values in `[curR + 1][curC]` and `[curR + 1][curC + 1]`
```python
def next_possible_char_for_this_pos():
if curChar == '0':
curChar = 'A' - 1
curChar++
while curChar <= 'F'
is_valid = check_pattern(
top=curChar,
bottom_left=pyramid[curR + 1][curC],
bottom_right=pyramid[curR + 1][curC + 1],
)
if is_valid:
break
if curChar > 'F':
curChar = '1'
```
## Caching
Purely solution space searching **without any cache** could **not pass all the testcase** *(due to `TLE`)*.
Therefore, we need to exploit the info produced during searching to **cache some impossible answer of sub-question** and use such cache in proper time.
### Set Cache
We could trigger set cache when **searching position change to the lower layer**.
Let's say, the position row index *(or we could say, layer index)* from `curR = 1` to `curR = 2`, then at this point, we could be sure the sub question using bottom sequence as current layer 2 is impossible.
![[251231_no_solution.png]]
This is because, if such sub question `B, D, C` have solution, the search position will finally go to the `curR = 0, curC = 0` and set `found = 1`, thus, the search is finished, and we found a valid solution for original question, and such solution use `B, D, C` as layer 2 elements.
> [!note]
>
> Here, sub question of a sequence means that: "If we could find a possible pyramid if the bottom is such sequence".
>
> For example, sub question using `B, D, C` as sequence means if we could find a valid pyramid that using `B, D, C` as the pyramid bottom.
### Use Cache
Based on analysis above, it's easy to know we could use cache when **searching position changes to higher layer**.
![[251231_use_cache.png]]
As the image above, when we goes from `[2][0]` to `[1][1]`, before start searching, we first check if the sub questions of layer 2: `B, D, C` is in the cache.
If cache hit, it means such **sub question has no solution** and we should **not wasting time searching further** anymore. Instead, we directly go back to `[2][0]` again, set it to next possible value *(for example from `B` to `C` in the image)* then keep searching.
> [!note]
>
> We **only need to cache the invalid sub questions**, thus, the cache could be stored in a set, e.g. `std::unordered_set<std::string> cache`. As long as a string sequence is in the cache *(could be checked using `cache.contains(str)`)*, we can sure it doesn't have solution.
> [!note]
>
> It's easy to proof **we don't need to cache the "valid" solution** of any sub question. Reusing example above, if the `B, D, C` sub sequence is valid as a pyramid bottom, then we will not even have a chance to cache it since the search procedure will reach the top of pyramid and declare `found = true`.
>
> In other word, if any sub question is valid in our definition, it must also indicate the original question solution is also being found.
## More About Cache
At the beginning, I'm actually thinking about another way of recording cache. That is, when we **find a valid value for position `[i][j]`,** then if we **use this position as pyramid top to consider the sub-pyramid**, then **all the layer should be able to considered a valid sequence** as a sub question.
![[251231_another_way_of_cache.png]]
Use the image above as an example, if during the searching procedure, we **found that `D` as a valid color for position `[2][1]`,** then we should be able to ensure the **layers of the sub-pyramid are all valid sequences as sub-question**, that is:
```
seq1 = C, D
seq2 = E, F, A
seq3 = ...
```
**All these sequences should be consider valid**, since when any of them is considered as the bottom, we **could found at least a valid pyramid that satisfies the constrain of the question** simply based on the sub-pyramid *(the green and blue part in the image)* we found.
> [!note]
>
> In this case, if we **can not find any valid value for position `[1][2]`,** we **can NOT say** conversely that **any layer for the sub-pyramid is not valid**.
>
> This is easy to understand, actually we could ensure `C, D` is not a valid pyramid bottom, however, that doesn't mean `E, F, A` is not valid, since it may have other available sequence other than `C, D` as the upper layer of `E, F, A`
-----
I tried writing solution code using this thought, triggering cache but it turns out I got `TLE`. The basic code logic I implement is like below:
```python
# if we should trigger cache for current position for now?
def should_trigger_cache(curR, curC) -> bool:
# only trigger cache when a position is being searched
# at the first time in current sub solution space
if currChar != '0':
return False
# first search, but no valid value for current position
# then do not cache
if next_possible_char_for_this_pos() == '1':
return False
return True
# perform caching for all sequences of sub pyramid
def set_cache_for_sub_pyramid(curR, curC):
for string in get_sub_pyramid_layers_as_string():
cache.add(seq=string, value=True)
```
Personally I guess the cost of caching sub-pyramid for every position every time it's first searched in a sub solution space is too high, but I can't figure out a better approach lol
# Code Implementation
```cpp
#include <algorithm>
#include <format>
#include <iostream>
#include <numeric>
#include <string>
#include <unordered_set>
#include <unordered_map>
#include <vector>
using std::cout, std::endl;
using std::format;
using std::vector, std::string;
bool debug = false;
/**
* Data structure to store pattern in question
*
* Init:
* - Use 3-char string to init (based on questoni definition)
* - Use three different char parameter to init
*
* Method:
* - Equal comparator
* - hash() function
*/
struct Pattern
{
char top;
char left;
char right;
Pattern(const string &data)
{
top = data[2];
left = data[0];
right = data[1];
}
Pattern(char top, char left, char right)
: top(top), left(left), right(right) {}
bool operator==(const Pattern &other) const
{
return top == other.top && left == other.left && right == other.right;
}
size_t hash() const
{
return std::hash<char>()(top) + std::hash<char>()(left) +
std::hash<char>()(right);
}
};
struct PatternHash
{
size_t operator()(const Pattern &p) const { return p.hash(); }
};
class PatternManager
{
private:
std::unordered_set<Pattern, PatternHash> mPatterns;
bool mPairs[6][6];
public:
PatternManager()
{
clear();
}
void add(const Pattern &p)
{
mPatterns.insert(p);
mPairs[p.left - 'A'][p.right - 'A'] = 1;
}
bool exists(const Pattern &p)
{
if (!mPairs[p.left - 'A'][p.right - 'A'])
{
return false;
}
return mPatterns.find(p) != mPatterns.end();
}
void clear()
{
mPatterns.clear();
for (int i = 0; i < 6; ++i)
{
for (int j = 0; j < 6; ++j)
{
mPairs[i][j] = 0;
}
}
}
};
// global variables
// statistics
unsigned bottomSize = 0;
string bottomString;
char pyramid[6][6]; // 0: not searched, A-F: searching, 1: finished
PatternManager pMgr;
// search temp
unsigned curR, curC;
bool found, finished;
class AnswerCache
{
private:
std::unordered_map<string, bool> mAllowedBottomcache;
string wholeRowToString(unsigned rowIdx)
{
string s = "";
for (int i = 0; i <= rowIdx; ++i)
{
s.push_back(pyramid[rowIdx][i]);
}
return s;
}
public:
AnswerCache() {}
void setCache()
{
mAllowedBottomcache[wholeRowToString(curR)] = false;
}
// false: not in cache, true: hit
int getCache(int rowIdx)
{
string rowStr = wholeRowToString(rowIdx);
return mAllowedBottomcache.contains(rowStr);
}
void clear()
{
mAllowedBottomcache.clear();
}
};
AnswerCache ansCache;
class Initializer
{
public:
// init variables and clear mMgr
void initVariables()
{
// init temp
curR = bottomSize - 2;
curC = bottomSize - 2;
found = 0;
finished = 0;
// clear manager
pMgr.clear();
ansCache.clear();
// clear answer cache
// init pyramid
for (int i = 0; i < 6; ++i)
{
for (int j = 0; j < 6; ++j)
{
pyramid[i][j] = '0';
}
}
}
// init bottomString and the pyramid array
void initPyramidBottom(const string &data)
{
bottomString = data;
for (int i = 0; i < bottomSize; ++i)
{
pyramid[bottomSize - 1][i] = data[i];
}
}
// fill data to mMgr
void initPattern(const vector<string> &allowed)
{
for (const auto &s : allowed)
{
pMgr.add(Pattern(s));
}
}
};
class Searcher
{
private:
bool deltaSearchpointer(bool forward)
{
// forward
if (forward)
{
if (curR <= 0 && curC <= 0)
{
return false;
}
if (curC > 0)
{
--curC;
}
else
{
--curR;
curC = curR;
}
return true;
}
// backward
else
{
if (curC >= bottomSize - 2 && curR >= bottomSize - 2)
{
return false;
}
if (curC < curR)
{
++curC;
}
else
{
++curR;
curC = 0;
}
return true;
}
}
char &curChar() { return pyramid[curR][curC]; }
char &leftChar() { return pyramid[curR + 1][curC]; }
char &rightChar() { return pyramid[curR + 1][curC + 1]; }
bool atTop() { return curR == curC && curC == 0; }
bool curValid()
{
return pMgr.exists(Pattern(curChar(), leftChar(), rightChar()));
}
void setToNextPossibleChar()
{
// search end
if (curChar() == '1')
{
return;
}
// search not begin
if (curChar() == '0')
{
curChar() = 'A';
if (curValid())
{
return;
}
}
++curChar();
while (curChar() <= 'F' && !curValid())
{
++curChar();
}
if (curChar() > 'F')
{
curChar() = '1';
}
}
void _search()
{
// already found answer
if (found || finished)
{
return;
}
// try use cache to check if we could skip current layer
// before we are about to start a new upper layer
if (curC == curR && curChar() == '0')
{
if (ansCache.getCache(curR + 1))
{
deltaSearchpointer(0);
return;
}
}
setToNextPossibleChar();
bool isDelta;
// this position finished
if (curChar() == '1')
{
isDelta = deltaSearchpointer(0);
// finished
if (!isDelta)
{
finished = 1;
}
// back to lower layer
if (curC == 0)
{
// remember this layer of pattern doesn't work
ansCache.setCache();
}
return;
}
// this position not finish searching
isDelta = deltaSearchpointer(1);
if (!isDelta)
{
found = 1;
}
else
{
curChar() = '0';
}
return;
}
public:
void search()
{
while (!found && !finished)
{
_search();
}
}
};
class Solution
{
public:
bool pyramidTransition(string bottom, vector<string> &allowed)
{
// initialization
bottomSize = bottom.size();
auto initer = Initializer();
initer.initVariables();
initer.initPyramidBottom(bottom);
initer.initPattern(allowed);
// search the answer
auto searcher = Searcher();
searcher.search();
return found;
}
};
```

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,6 @@
---
title: Leetcode Questions
date: 2025-12-25
---
Some notes about Leetcode questions.

View File

@@ -0,0 +1,42 @@
---
date: 2025-12-26
tags:
- Leetcode
---
We know that Leetcode puts the solution function into a class. Let's check example below:
```cpp
int gv = 0;
class Solution {
public:
int returnSecondElem(int arr[]) {
gv += 1;
cout << gv; // expected to be 1 in each case
return arr[gv];
}
};
```
Here we initialize a global variable `gv` and use it in the solution function `returnSecondElem()`. In this case, we may expected that for each test case, the `cout << gv` will print `1` and the second element of the array is returned.
However, this is not the case. Since `gv` is global variable, and Leetcode seems to use single `Solution` instance for solving all test cases, when first test case finished, the `gv` already became `1`, so for the second test case, program will print `2` and third element will be returned.
-----
If we want to use global variable, we may also want to initialize it at the beginning of the solution method:
```cpp
int gv = 0;
class Solution {
public:
int returnSecondElem(int arr[]) {
// always initialize here!
gv = 0;
gv += 1;
cout << gv;
return arr[gv];
}
};
```

Binary file not shown.

15
content/index.md Normal file
View File

@@ -0,0 +1,15 @@
---
title: Oyasumi Coding Notes
tags:
- Home
- Pages
---
Hi everyone! Here is my small blogs for coding, you could also checkout my personal blog [nfblogs.com](https://nfblogs.com) if you want, have a nice day!
- Categories
- [[Leetcode Questions/index|Leetcode Questions]]
- [[Classic Questions/index|Classic Questions]]
- Others
- [[Be careful When Using Global Variables in Leetcode]]
- Todo
- Heap