init: init commit, build
This commit is contained in:
@@ -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;
|
||||
}
|
||||
};
|
||||
```
|
||||
270
content/Classic Questions/Maximum Task Value.md
Normal file
270
content/Classic Questions/Maximum Task Value.md
Normal 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;
|
||||
}
|
||||
};
|
||||
```
|
||||
@@ -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;
|
||||
}
|
||||
};
|
||||
```
|
||||
BIN
content/Classic Questions/assets/251227_breakpoint.jpg
LFS
Normal file
BIN
content/Classic Questions/assets/251227_breakpoint.jpg
LFS
Normal file
Binary file not shown.
5
content/Classic Questions/index.md
Normal file
5
content/Classic Questions/index.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
title: Classic Questions
|
||||
date: 2025-12-26
|
||||
---
|
||||
Some of the classic question templates in coding questions.
|
||||
@@ -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;
|
||||
}
|
||||
};
|
||||
```
|
||||
347
content/Leetcode Questions/Meeting Rooms III.md
Normal file
347
content/Leetcode Questions/Meeting Rooms III.md
Normal 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();
|
||||
}
|
||||
};
|
||||
```
|
||||
75
content/Leetcode Questions/Minimum Penalty For a Shop.md
Normal file
75
content/Leetcode Questions/Minimum Penalty For a Shop.md
Normal 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;
|
||||
}
|
||||
};
|
||||
```
|
||||
6
content/Leetcode Questions/index.md
Normal file
6
content/Leetcode Questions/index.md
Normal file
@@ -0,0 +1,6 @@
|
||||
---
|
||||
title: Leetcode Questions
|
||||
date: 2025-12-25
|
||||
---
|
||||
|
||||
Some notes about Leetcode questions.
|
||||
@@ -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];
|
||||
}
|
||||
};
|
||||
```
|
||||
15
content/index.md
Normal file
15
content/index.md
Normal 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](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
|
||||
Reference in New Issue
Block a user