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.