← Home

1235. Maximum Profit in Job Scheduling

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
dynamic programmingC++Markdown
123

This is one of those problems where the clean idea matters more than the amount of code. For 1235. Maximum Profit in Job Scheduling, the solution in this repository is mainly a dynamic programming solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: dynamic programming.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are sort_indexes, idx, reorder, jobScheduling, tmp.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 196 ms, faster than 45.83% of C++ online submissions for Maximum Profit in Job Scheduling.
02//Memory Usage: 14.9 MB, less than 100.00% of C++ online submissions for Maximum Profit in Job Scheduling.
03class Solution {
04public:
05    template <typename T>
06    vector<size_t> sort_indexes(const vector<T> &v) {
07
08      // initialize original index locations
09      vector<size_t> idx(v.size());
10      iota(idx.begin(), idx.end(), 0);
11
12      // sort indexes based on comparing values in v
13      sort(idx.begin(), idx.end(),
14           [&v](size_t i1, size_t i2) {return v[i1] < v[i2];});
15
16      return idx;
17    };
18    
19    template< typename order_iterator, typename value_iterator >
20    void reorder( order_iterator order_begin, order_iterator order_end, value_iterator v )  {   
21        typedef typename std::iterator_traits< value_iterator >::value_type value_t;
22        typedef typename std::iterator_traits< order_iterator >::value_type index_t;
23        typedef typename std::iterator_traits< order_iterator >::difference_type diff_t;
24
25        diff_t remaining = order_end - 1 - order_begin;
26        for ( index_t s = index_t(), d; remaining > 0; ++ s ) {
27            for ( d = order_begin[s]; d > s; d = order_begin[d] ) ;
28            if ( d == s ) {
29                -- remaining;
30                value_t temp = v[s];
31                while ( d = order_begin[d], d != s ) {
32                    std::swap( temp, v[d] );
33                    -- remaining;
34                }
35                v[s] = temp;
36            }
37        }
38    };
39    
40    int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {
41        int N = startTime.size();
42        
43        vector<size_t> ixs = sort_indexes(startTime);
44        vector<size_t> tmp(N);
45        for(int i = 0; i < N; i++){
46            int ix = ixs[i];
47            tmp[ix] = i;
48        }
49        ixs = tmp;
50        
51        reorder(ixs.begin(), ixs.end(), startTime.begin());
52        reorder(ixs.begin(), ixs.end(), endTime.begin());
53        reorder(ixs.begin(), ixs.end(), profit.begin());
54        
55        vector<int> dp(N, 0);
56        
57        for(int i = N-1; i >= 0; i--){
58            int curEnd = endTime[i];
59            //lower_bound: find the smallest number >= x
60            auto afterIt = lower_bound(startTime.begin(), startTime.end(), curEnd);
61            int afterIdx = -1;
62            if(afterIt != startTime.end()){
63                afterIdx = afterIt - startTime.begin();
64            }
65            dp[i] = max((i+1 < N ? dp[i+1] : 0), 
66                        profit[i] + (afterIdx >= 0 ? dp[afterIdx] : 0));
67        }
68        
69//         copy(ixs.begin(), ixs.end(), ostream_iterator<int>(cout, " "));
70//         cout << endl;
71        
72//         copy(startTime.begin(), startTime.end(), ostream_iterator<int>(cout, " "));
73//         cout << endl;
74        
75//         copy(endTime.begin(), endTime.end(), ostream_iterator<int>(cout, " "));
76//         cout << endl;
77        
78//         copy(profit.begin(), profit.end(), ostream_iterator<int>(cout, " "));
79//         cout << endl;
80        
81//         copy(dp.begin(), dp.end(), ostream_iterator<int>(cout, " "));
82//         cout << endl;
83        
84        return dp[0];
85    }
86};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.