- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 40 lines of C++ from the credited upstream file 1235-2.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 3 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct Job {2 int startTime;3 int endTime;4 int profit;5};6 7class Solution {8 public:9 int jobScheduling(vector<int>& startTime, vector<int>& endTime,10 vector<int>& profit) {11 const int n = startTime.size();12 13 vector<int> dp(n + 1);14 vector<Job> jobs;15 16 for (int i = 0; i < n; ++i)17 jobs.emplace_back(startTime[i], endTime[i], profit[i]);18 19 ranges::sort(jobs, ranges::less{},20 [](const Job& job) { return job.startTime; });21 22 for (int i = 0; i < n; ++i)23 startTime[i] = jobs[i].startTime;24 25 for (int i = n - 1; i >= 0; --i) {26 const int j = firstGreaterEqual(startTime, i + 1, jobs[i].endTime);27 const int pick = jobs[i].profit + dp[j];28 const int skip = dp[i + 1];29 dp[i] = max(pick, skip);30 }31 32 return dp[0];33 }34 35 int firstGreaterEqual(const vector<int>& arr, int startFrom, int target) {36 return lower_bound(arr.begin() + startFrom, arr.end(), target) -37 arr.begin();38 }39};40