Given a 2D array jobs[][] of order n*3, where each element jobs[i] defines start time, end time, and the profit associated with the job. The task is to find the maximum profit you can take such that there are no two jobs with overlapping time ranges.
Note: If the job ends at time X, it is allowed to choose another job that starts at time X
.
Examples:
Input: jobs[][] = [[1, 2, 50],
[3, 5, 20],
[6, 19, 100],
[2, 100, 200]]
Output: 250
Explanation: The first and fourth jobs with the time range [1, 2] and [2, 100] can be chosen to give maximum profit of 50 + 200 = 250.
Input: jobs[][] = [[1, 3, 60],
[2, 5, 50],
[4, 6, 70],
[5, 7, 30]]
Output: 130
Explanation: The first and third jobs with the time range [1, 3] and [4, 6] can be chosen to give maximum profit of 60 + 70 = 130.
[Naive Approach] - Using Recursion - O(n ^ n) Time and O(n) Space
The idea is to schedule the jobs in all possible ways using recursion and find the profit associated with each scheduling, the maximum among them is the result. To do so, sort the jobs in ascending order based on their start time and for each job, consider the job's profit, and find the maximum profit from all the next non-overlapping jobs i.e. maxProfit(i, jobs) = max(maxProfit(j, jobs)), where i < j < n.
C++
// C++ program to implement
// Weighted Job Scheduling
#include <bits/stdc++.h>
using namespace std;
// Recusive function to find the maximum
// profit from weighted job scheduling
int maxProfitRecur(vector<vector<int>> &jobs,
int ind, int last) {
if (ind == jobs.size())
return 0;
// skip the current job
int ans = maxProfitRecur(jobs, ind+1, last);
// if start of current is greater than or
// equals to end time of previous job
if(jobs[ind][0] >= last)
ans = max(ans, jobs[ind][2] +
maxProfitRecur(jobs, ind+1, jobs[ind][1]));
return ans;
}
// Function to find the maximum profit
// from weighted job scheduling
int maxProfit(vector<vector<int>> &jobs) {
int n = jobs.size();
// Sort the jobs based on start time
sort(jobs.begin(), jobs.end());
return maxProfitRecur(jobs, 0, -1);
}
int main() {
vector<vector<int>> jobs = {
{1, 2, 50},
{3, 5, 20},
{6, 19, 100},
{2, 100, 200}
};
cout << maxProfit(jobs);
return 0;
}
Java
// Java program to implement
// Weighted Job Scheduling
import java.util.*;
class GfG {
// Recursive function to find the maximum
// profit from weighted job scheduling
static int maxProfitRecur(int[][] jobs,
int ind, int last) {
if (ind == jobs.length)
return 0;
// skip the current job
int ans = maxProfitRecur(jobs, ind + 1, last);
// if start of current is greater than or
// equals to end time of previous job
if (jobs[ind][0] >= last)
ans = Math.max(ans, jobs[ind][2] +
maxProfitRecur(jobs, ind + 1, jobs[ind][1]));
return ans;
}
// Function to find the maximum profit
// from weighted job scheduling
static int maxProfit(int[][] jobs) {
// Sort the jobs based on start time
Arrays.sort(jobs, (a, b) ->
Integer.compare(a[0], b[0]));
return maxProfitRecur(jobs, 0, -1);
}
public static void main(String[] args) {
int[][] jobs = {
{1, 2, 50},
{3, 5, 20},
{6, 19, 100},
{2, 100, 200}
};
System.out.println(maxProfit(jobs));
}
}
Python
# Python program to implement
# Weighted Job Scheduling
# Recursive function to find the maximum
# profit from weighted job scheduling
def maxProfitRecur(jobs, ind, last):
if ind == len(jobs):
return 0
# skip the current job
ans = maxProfitRecur(jobs, ind + 1, last)
# if start of current is greater than or
# equals to end time of previous job
if jobs[ind][0] >= last:
ans = max(ans, jobs[ind][2] +
maxProfitRecur(jobs, ind + 1, jobs[ind][1]))
return ans
# Function to find the maximum profit
# from weighted job scheduling
def maxProfit(jobs):
# Sort the jobs based on start time
jobs.sort()
return maxProfitRecur(jobs, 0, -1)
if __name__ == "__main__":
jobs = [
[1, 2, 50],
[3, 5, 20],
[6, 19, 100],
[2, 100, 200]
]
print(maxProfit(jobs))
C#
// C# program to implement
// Weighted Job Scheduling
using System;
using System.Collections.Generic;
class GfG {
// Recursive function to find the maximum
// profit from weighted job scheduling
static int MaxProfitRecur(int[][] jobs,
int ind, int last) {
if (ind == jobs.Length)
return 0;
// skip the current job
int ans = MaxProfitRecur(jobs, ind + 1, last);
// if start of current is greater than or
// equals to end time of previous job
if (jobs[ind][0] >= last)
ans = Math.Max(ans, jobs[ind][2] +
MaxProfitRecur(jobs, ind + 1, jobs[ind][1]));
return ans;
}
// Function to find the maximum profit
// from weighted job scheduling
static int MaxProfit(int[][] jobs) {
// Sort the jobs based on start time
Array.Sort(jobs, (a, b) => a[0].CompareTo(b[0]));
return MaxProfitRecur(jobs, 0, -1);
}
static void Main(string[] args) {
int[][] jobs = {
new int[] {1, 2, 50},
new int[] {3, 5, 20},
new int[] {6, 19, 100},
new int[] {2, 100, 200}
};
Console.WriteLine(MaxProfit(jobs));
}
}
JavaScript
// JavaScript program to implement
// Weighted Job Scheduling
// Recursive function to find the maximum
// profit from weighted job scheduling
function maxProfitRecur(jobs, ind, last) {
if (ind === jobs.length)
return 0;
// skip the current job
let ans = maxProfitRecur(jobs, ind + 1, last);
// if start of current is greater than or
// equals to end time of previous job
if (jobs[ind][0] >= last)
ans = Math.max(ans, jobs[ind][2] +
maxProfitRecur(jobs, ind + 1, jobs[ind][1]));
return ans;
}
// Function to find the maximum profit
// from weighted job scheduling
function maxProfit(jobs) {
// Sort the jobs based on start time
jobs.sort((a, b) => a[0] - b[0]);
return maxProfitRecur(jobs, 0, -1);
}
// Driver Code
const jobs = [
[1, 2, 50],
[3, 5, 20],
[6, 19, 100],
[2, 100, 200]
];
console.log(maxProfit(jobs));
[Expected Approach - 1] - Using Memoization - O(n ^ 2) Time and O(n) Space
The above approach can be optimized using memoization to avoid computing the overlapping subproblems multiple times. To do so, create an array memo[] of size n, where each element memo[i] stores the maximum possible profit for jobs in range [i, n-1]. For each recursive call, check if the subproblem is already computed, if so return the stored value, else proceed similar to above approach.
C++
// C++ program to implement
// Weighted Job Scheduling
#include <bits/stdc++.h>
using namespace std;
// Recusive function to find the maximum
// profit from weighted job scheduling
int maxProfitRecur(vector<vector<int>> &jobs,
int ind, int last, vector<int> &memo) {
if (ind == jobs.size())
return 0;
// if the job can be taken
if(jobs[ind][0] >= last) {
// if the value is not calculated
if(memo[ind] == -1) {
// take the job
memo[ind] = jobs[ind][2] +
maxProfitRecur(jobs, ind+1, jobs[ind][1], memo);
// leave the job and find max
memo[ind] = max(memo[ind],
maxProfitRecur(jobs, ind+1, last, memo));
}
return memo[ind];
}
// if the job can't be taken
return maxProfitRecur(jobs, ind+1, last, memo);
}
// Function to find the maximum profit
// from weighted job scheduling
int maxProfit(vector<vector<int>> &jobs) {
int n = jobs.size();
// Sort the jobs based on start time
sort(jobs.begin(), jobs.end());
// create memoization array and
// initialize it with -1
vector<int> memo(n, -1);
return maxProfitRecur(jobs, 0, -1, memo);
}
int main() {
vector<vector<int>> jobs = {
{1, 2, 50},
{3, 5, 20},
{6, 19, 100},
{2, 100, 200}
};
cout << maxProfit(jobs);
return 0;
}
Java
// Java program to implement
// Weighted Job Scheduling
import java.util.*;
class GfG {
// Recursive function to find the maximum
// profit from weighted job scheduling
static int maxProfitRecur(int[][] jobs,
int ind, int last, int[] memo) {
if (ind == jobs.length)
return 0;
// if the job can be taken
if (jobs[ind][0] >= last) {
// if the value is not calculated
if (memo[ind] == -1) {
// take the job
memo[ind] = jobs[ind][2] +
maxProfitRecur(jobs, ind + 1, jobs[ind][1], memo);
// leave the job and find max
memo[ind] = Math.max(memo[ind],
maxProfitRecur(jobs, ind + 1, last, memo));
}
return memo[ind];
}
// if the job can't be taken
return maxProfitRecur(jobs, ind + 1, last, memo);
}
// Function to find the maximum profit
// from weighted job scheduling
static int maxProfit(int[][] jobs) {
int n = jobs.length;
// Sort the jobs based on start time
Arrays.sort(jobs, (a, b) ->
Integer.compare(a[0], b[0]));
// create memoization array and
// initialize it with -1
int[] memo = new int[n];
Arrays.fill(memo, -1);
return maxProfitRecur(jobs, 0, -1, memo);
}
public static void main(String[] args) {
int[][] jobs = {
{1, 2, 50},
{3, 5, 20},
{6, 19, 100},
{2, 100, 200}
};
System.out.println(maxProfit(jobs));
}
}
Python
# Python program to implement
# Weighted Job Scheduling
# Recursive function to find the maximum
# profit from weighted job scheduling
def maxProfitRecur(jobs, ind, last, memo):
if ind == len(jobs):
return 0
# if the job can be taken
if jobs[ind][0] >= last:
# if the value is not calculated
if memo[ind] == -1:
# take the job
memo[ind] = jobs[ind][2] + \
maxProfitRecur(jobs, ind + 1, jobs[ind][1], memo)
# leave the job and find max
memo[ind] = max(memo[ind],
maxProfitRecur(jobs, ind + 1, last, memo))
return memo[ind]
# if the job can't be taken
return maxProfitRecur(jobs, ind + 1, last, memo)
# Function to find the maximum profit
# from weighted job scheduling
def maxProfit(jobs):
# Sort the jobs based on start time
jobs.sort()
# create memoization array and
# initialize it with -1
memo = [-1] * len(jobs)
return maxProfitRecur(jobs, 0, -1, memo)
if __name__ == "__main__":
jobs = [
[1, 2, 50],
[3, 5, 20],
[6, 19, 100],
[2, 100, 200]
]
print(maxProfit(jobs))
C#
// C# program to implement
// Weighted Job Scheduling
using System;
using System.Collections.Generic;
class GfG {
// Recursive function to find the maximum
// profit from weighted job scheduling
static int MaxProfitRecur(int[][] jobs,
int ind, int last, int[] memo) {
if (ind == jobs.Length)
return 0;
// if the job can be taken
if (jobs[ind][0] >= last) {
// if the value is not calculated
if (memo[ind] == -1) {
// take the job
memo[ind] = jobs[ind][2] +
MaxProfitRecur(jobs, ind + 1, jobs[ind][1], memo);
// leave the job and find max
memo[ind] = Math.Max(memo[ind],
MaxProfitRecur(jobs, ind + 1, last, memo));
}
return memo[ind];
}
// if the job can't be taken
return MaxProfitRecur(jobs, ind + 1, last, memo);
}
// Function to find the maximum profit
// from weighted job scheduling
static int MaxProfit(int[][] jobs) {
int n = jobs.Length;
// Sort the jobs based on start time
Array.Sort(jobs, (a, b) => a[0].CompareTo(b[0]));
// create memoization array and
// initialize it with -1
int[] memo = new int[n];
Array.Fill(memo, -1);
return MaxProfitRecur(jobs, 0, -1, memo);
}
static void Main(string[] args) {
int[][] jobs = {
new int[] {1, 2, 50},
new int[] {3, 5, 20},
new int[] {6, 19, 100},
new int[] {2, 100, 200}
};
Console.WriteLine(MaxProfit(jobs));
}
}
JavaScript
// JavaScript program to implement
// Weighted Job Scheduling
// Recursive function to find the maximum
// profit from weighted job scheduling
function maxProfitRecur(jobs, ind, last, memo) {
if (ind === jobs.length)
return 0;
// if the job can be taken
if (jobs[ind][0] >= last) {
// if the value is not calculated
if (memo[ind] === -1) {
// take the job
memo[ind] = jobs[ind][2] +
maxProfitRecur(jobs, ind + 1, jobs[ind][1], memo);
// leave the job and find max
memo[ind] = Math.max(memo[ind],
maxProfitRecur(jobs, ind + 1, last, memo));
}
return memo[ind];
}
// if the job can't be taken
return maxProfitRecur(jobs, ind + 1, last, memo);
}
// Function to find the maximum profit
// from weighted job scheduling
function maxProfit(jobs) {
// Sort the jobs based on start time
jobs.sort((a, b) => a[0] - b[0]);
// create memoization array and
// initialize it with -1
const memo = Array(jobs.length).fill(-1);
return maxProfitRecur(jobs, 0, -1, memo);
}
const jobs = [
[1, 2, 50],
[3, 5, 20],
[6, 19, 100],
[2, 100, 200]
];
console.log(maxProfit(jobs));
[Expected Approach - 2] - Using Tabulation - O(n * n) Time and O(n) Space
The above approach can further be optimized using bottom-up dp (tabulation) to minimize the space required for recursive stack. To do so, create an array dp[] of size n, where each element dp[i] stores the maximum possible profit for jobs in range [i, n-1]. Start from the last index i.e. n-1, and for each index i compute the maximum profit for subarray i to n-1 and store the result in dp[i]. The maximum of all the values stored in dp[] is the result.
C++
// C++ program to implement
// Weighted Job Scheduling
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum profit
// from weighted job scheduling
int maxProfit(vector<vector<int>> &jobs) {
int n = jobs.size();
// Sort the jobs based on start time
sort(jobs.begin(), jobs.end());
// create a dp table
vector<int> dp(n);
// stores the maximum profit
int res = 0;
// iterate over all the jobs
for(int i = n-1; i >= 0; i--) {
dp[i] = jobs[i][2];
// find the maximum profit
for(int j = i+1; j < n; j++) {
if(jobs[i][1] <= jobs[j][0]) {
dp[i] = max(dp[i], dp[j] + jobs[i][2]);
}
}
res = max(res, dp[i]);
}
return res;
}
int main() {
vector<vector<int>> jobs = {
{1, 2, 50},
{3, 5, 20},
{6, 19, 100},
{2, 100, 200}
};
cout << maxProfit(jobs);
return 0;
}
Java
// Java program to implement
// Weighted Job Scheduling
import java.util.*;
class GfG {
// Function to find the maximum profit
// from weighted job scheduling
static int maxProfit(int[][] jobs) {
int n = jobs.length;
// Sort the jobs based on start time
Arrays.sort(jobs, (a, b) ->
Integer.compare(a[0], b[0]));
// create a dp table
int[] dp = new int[n];
// stores the maximum profit
int res = 0;
// iterate over all the jobs
for (int i = n - 1; i >= 0; i--) {
dp[i] = jobs[i][2];
// find the maximum profit
for (int j = i + 1; j < n; j++) {
if (jobs[i][1] <= jobs[j][0]) {
dp[i] = Math.max(dp[i], dp[j] + jobs[i][2]);
}
}
res = Math.max(res, dp[i]);
}
return res;
}
public static void main(String[] args) {
int[][] jobs = {
{1, 2, 50},
{3, 5, 20},
{6, 19, 100},
{2, 100, 200}
};
System.out.println(maxProfit(jobs));
}
}
Python
# Python program to implement
# Weighted Job Scheduling
# Function to find the maximum profit
# from weighted job scheduling
def maxProfit(jobs):
n = len(jobs)
# Sort the jobs based on start time
jobs.sort()
# create a dp table
dp = [0] * n
# stores the maximum profit
res = 0
# iterate over all the jobs
for i in range(n - 1, -1, -1):
dp[i] = jobs[i][2]
# find the maximum profit
for j in range(i + 1, n):
if jobs[i][1] <= jobs[j][0]:
dp[i] = max(dp[i], dp[j] + jobs[i][2])
res = max(res, dp[i])
return res
if __name__ == "__main__":
jobs = [
[1, 2, 50],
[3, 5, 20],
[6, 19, 100],
[2, 100, 200]
]
print(maxProfit(jobs))
C#
// C# program to implement
// Weighted Job Scheduling
using System;
using System.Linq;
class GfG {
// Function to find the maximum profit
// from weighted job scheduling
static int MaxProfit(int[][] jobs) {
int n = jobs.Length;
// Sort the jobs based on start time
Array.Sort(jobs, (a, b) => a[0].CompareTo(b[0]));
// create a dp table
int[] dp = new int[n];
// stores the maximum profit
int res = 0;
// iterate over all the jobs
for (int i = n - 1; i >= 0; i--) {
dp[i] = jobs[i][2];
// find the maximum profit
for (int j = i + 1; j < n; j++) {
if (jobs[i][1] <= jobs[j][0]) {
dp[i] = Math.Max(dp[i], dp[j] + jobs[i][2]);
}
}
res = Math.Max(res, dp[i]);
}
return res;
}
static void Main(string[] args) {
int[][] jobs = {
new int[] {1, 2, 50},
new int[] {3, 5, 20},
new int[] {6, 19, 100},
new int[] {2, 100, 200}
};
Console.WriteLine(MaxProfit(jobs));
}
}
JavaScript
// JavaScript program to implement
// Weighted Job Scheduling
// Function to find the maximum profit
// from weighted job scheduling
function maxProfit(jobs) {
const n = jobs.length;
// Sort the jobs based on start time
jobs.sort((a, b) => a[0] - b[0]);
// create a dp table
const dp = new Array(n).fill(0);
// stores the maximum profit
let res = 0;
// iterate over all the jobs
for (let i = n - 1; i >= 0; i--) {
dp[i] = jobs[i][2];
// find the maximum profit
for (let j = i + 1; j < n; j++) {
if (jobs[i][1] <= jobs[j][0]) {
dp[i] = Math.max(dp[i], dp[j] + jobs[i][2]);
}
}
res = Math.max(res, dp[i]);
}
return res;
}
const jobs = [
[1, 2, 50],
[3, 5, 20],
[6, 19, 100],
[2, 100, 200]
];
console.log(maxProfit(jobs));
[Optimized Approach - 1] - Using Binary Search with Tabulation - O(n * log(n)) Time and O(n) Space
In above approach, for each index i, we are iterating from index i + 1 to n-1 to find the job with greater start time and maximum profit. As the jobs are sorted in ascending order, instead of iterating over all the elements we can perform binary search to find the index of the job with start time greater than or equal to end time of current job. Now dp[i] will store the maximum of dp[i] and dp[i+1]. And the final result will be stored in dp[0].
C++
// C++ program to implement
// Weighted Job Scheduling
#include <bits/stdc++.h>
using namespace std;
// Function to find the closest next job.
int findNextJob(int i, vector<vector<int>> &jobs) {
int end = jobs[i][1];
int ans = jobs.size();
int s = i + 1, e = jobs.size() - 1;
while (s <= e) {
int mid = s + (e - s) / 2;
if (jobs[mid][0] >= end) {
ans = mid;
e = mid - 1;
}
else {
s = mid + 1;
}
}
return ans;
}
// Function to find the maximum profit
// from weighted job scheduling
int maxProfit(vector<vector<int>> &jobs) {
int n = jobs.size();
// Sort the jobs based on start time
sort(jobs.begin(), jobs.end());
// create a dp table
vector<int> dp(n);
// iterate over all the jobs
for(int i = n-1; i >= 0; i--) {
dp[i] = jobs[i][2];
// find the index of next job
int next = findNextJob(i, jobs);
// if next job exists
if(next < n) {
dp[i] += dp[next];
}
// store the maximum profit
if(i < n-1)
dp[i] = max(dp[i], dp[i+1]);
}
return dp[0];
}
int main() {
vector<vector<int>> jobs = {
{1, 2, 50},
{3, 5, 20},
{6, 19, 100},
{2, 100, 200}
};
cout << maxProfit(jobs);
return 0;
}
Java
// Java program to implement
// Weighted Job Scheduling
import java.util.*;
class GfG {
// Function to find the closest next job.
static int findNextJob(int i, int[][] jobs) {
int end = jobs[i][1];
int ans = jobs.length;
int s = i + 1, e = jobs.length - 1;
while (s <= e) {
int mid = s + (e - s) / 2;
if (jobs[mid][0] >= end) {
ans = mid;
e = mid - 1;
} else {
s = mid + 1;
}
}
return ans;
}
// Function to find the maximum profit
// from weighted job scheduling
static int maxProfit(int[][] jobs) {
int n = jobs.length;
// Sort the jobs based on start time
Arrays.sort(jobs, (a, b) -> Integer.compare(a[0], b[0]));
// create a dp table
int[] dp = new int[n];
// iterate over all the jobs
for (int i = n - 1; i >= 0; i--) {
dp[i] = jobs[i][2];
// find the index of next job
int next = findNextJob(i, jobs);
// if next job exists
if (next < n) {
dp[i] += dp[next];
}
// store the maximum profit
if (i < n - 1) {
dp[i] = Math.max(dp[i], dp[i + 1]);
}
}
return dp[0];
}
public static void main(String[] args) {
int[][] jobs = {
{1, 2, 50},
{3, 5, 20},
{6, 19, 100},
{2, 100, 200}
};
System.out.println(maxProfit(jobs));
}
}
Python
# Python program to implement
# Weighted Job Scheduling
# Function to find the closest next job.
def findNextJob(i, jobs):
end = jobs[i][1]
ans = len(jobs)
s, e = i + 1, len(jobs) - 1
while s <= e:
mid = s + (e - s) // 2
if jobs[mid][0] >= end:
ans = mid
e = mid - 1
else:
s = mid + 1
return ans
# Function to find the maximum profit
# from weighted job scheduling
def maxProfit(jobs):
n = len(jobs)
# Sort the jobs based on start time
jobs.sort()
# create a dp table
dp = [0] * n
# iterate over all the jobs
for i in range(n - 1, -1, -1):
dp[i] = jobs[i][2]
# find the index of next job
next = findNextJob(i, jobs)
# if next job exists
if next < n:
dp[i] += dp[next]
# store the maximum profit
if i < n - 1:
dp[i] = max(dp[i], dp[i + 1])
return dp[0]
if __name__ == "__main__":
jobs = [
[1, 2, 50],
[3, 5, 20],
[6, 19, 100],
[2, 100, 200]
]
print(maxProfit(jobs))
C#
// C# program to implement
// Weighted Job Scheduling
using System;
class GfG {
// Function to find the closest next job.
static int FindNextJob(int i, int[][] jobs) {
int end = jobs[i][1];
int ans = jobs.Length;
int s = i + 1, e = jobs.Length - 1;
while (s <= e) {
int mid = s + (e - s) / 2;
if (jobs[mid][0] >= end) {
ans = mid;
e = mid - 1;
} else {
s = mid + 1;
}
}
return ans;
}
// Function to find the maximum profit
// from weighted job scheduling
static int MaxProfit(int[][] jobs) {
int n = jobs.Length;
// Sort the jobs based on start time
Array.Sort(jobs, (a, b) => a[0].CompareTo(b[0]));
// create a dp table
int[] dp = new int[n];
// iterate over all the jobs
for (int i = n - 1; i >= 0; i--) {
dp[i] = jobs[i][2];
// find the index of next job
int next = FindNextJob(i, jobs);
// if next job exists
if (next < n) {
dp[i] += dp[next];
}
// store the maximum profit
if (i < n - 1) {
dp[i] = Math.Max(dp[i], dp[i + 1]);
}
}
return dp[0];
}
public static void Main(string[] args) {
int[][] jobs = {
new int[] {1, 2, 50},
new int[] {3, 5, 20},
new int[] {6, 19, 100},
new int[] {2, 100, 200}
};
Console.WriteLine(MaxProfit(jobs));
}
}
JavaScript
// JavaScript program to implement
// Weighted Job Scheduling
// Function to find the closest next job.
function findNextJob(i, jobs) {
const end = jobs[i][1];
let ans = jobs.length;
let s = i + 1, e = jobs.length - 1;
while (s <= e) {
const mid = s + Math.floor((e - s) / 2);
if (jobs[mid][0] >= end) {
ans = mid;
e = mid - 1;
} else {
s = mid + 1;
}
}
return ans;
}
// Function to find the maximum profit
// from weighted job scheduling
function maxProfit(jobs) {
const n = jobs.length;
// Sort the jobs based on start time
jobs.sort((a, b) => a[0] - b[0]);
// create a dp table
const dp = new Array(n).fill(0);
// iterate over all the jobs
for (let i = n - 1; i >= 0; i--) {
dp[i] = jobs[i][2];
// find the index of next job
const next = findNextJob(i, jobs);
// if next job exists
if (next < n) {
dp[i] += dp[next];
}
// store the maximum profit
if (i < n - 1) {
dp[i] = Math.max(dp[i], dp[i + 1]);
}
}
return dp[0];
}
// Main Function
const jobs = [
[1, 2, 50],
[3, 5, 20],
[6, 19, 100],
[2, 100, 200]
];
console.log(maxProfit(jobs));
[Optimized Approach - 2] - Using Binary Search with Memoization - O(n * log(n)) Time and O(n) Space
Similar to the above approach, binary search can be implemented on memoization approach to reduce the iterative calls. This approach has been discussed in artice Weighted Job Scheduling in O(n Log n) time.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem