The Wayback Machine - https://web.archive.org/web/20241118043703/https://www.geeksforgeeks.org/weighted-job-scheduling/
Open In App

Weighted Job Scheduling

Last Updated : 23 Mar, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given N jobs where every job is represented by following three elements of it.

  1. Start Time
  2. Finish Time
  3. Profit or Value Associated (>= 0)

Find the maximum profit subset of jobs such that no two jobs in the subset overlap. 

Example: 

Input: Number of Jobs n = 4
       Job Details {Start Time, Finish Time, Profit}
       Job 1:  {1, 2, 50} 
       Job 2:  {3, 5, 20}
       Job 3:  {6, 19, 100}
       Job 4:  {2, 100, 200}
Output: The maximum profit is 250.
We can get the maximum profit by scheduling jobs 1 and 4.
Note that there is longer schedules possible Jobs 1, 2 and 3 
but the profit with this schedule is 20+50+100 which is less than 250.
Recommended Practice

A simple version of this problem is discussed here where every job has the same profit or value. The Greedy Strategy for activity selection doesn’t work here as a schedule with more jobs may have smaller profit or value.

The above problem can be solved using the following recursive solution.  

1) First sort jobs according to finish time.
2) Now apply following recursive process. 
   // Here arr[] is array of n jobs
   findMaximumProfit(arr[], n)
   {
     a) if (n == 1) return arr[0];
     b) Return the maximum of following two profits.
         (i) Maximum profit by excluding current job, i.e., 
             findMaximumProfit(arr, n-1)
         (ii) Maximum profit by including the current job            
   }

How to find the profit including current job?
The idea is to find the latest job before the current job (in 
sorted array) that doesn't conflict with current job 'arr[n-1]'. 
Once we find such a job, we recur for all jobs till that job and
add profit of current job to result.
In the above example, "job 1" is the latest non-conflicting
for "job 4" and "job 2" is the latest non-conflicting for "job 3".

The following is the implementation of the above naive recursive method. 

C++




// C++ program for weighted job scheduling using Naive Recursive Method
#include <iostream>
#include <algorithm>
using namespace std;
 
// A job has start time, finish time and profit.
struct Job
{
    int start, finish, profit;
};
 
// A utility function that is used for sorting events
// according to finish time
bool jobComparator(Job s1, Job s2)
{
    return (s1.finish < s2.finish);
}
 
// Find the latest job (in sorted array) that doesn't
// conflict with the job[i]. If there is no compatible job,
// then it returns -1.
int latestNonConflict(Job arr[], int i)
{
    for (int j=i-1; j>=0; j--)
    {
        if (arr[j].finish <= arr[i-1].start)
            return j;
    }
    return -1;
}
 
// A recursive function that returns the maximum possible
// profit from given array of jobs.  The array of jobs must
// be sorted according to finish time.
int findMaxProfitRec(Job arr[], int n)
{
    // Base case
    if (n == 1) return arr[n-1].profit;
 
    // Find profit when current job is included
    int inclProf = arr[n-1].profit;
    int i = latestNonConflict(arr, n);
    if (i != -1)
      inclProf += findMaxProfitRec(arr, i+1);
 
    // Find profit when current job is excluded
    int exclProf = findMaxProfitRec(arr, n-1);
 
    return max(inclProf,  exclProf);
}
 
// The main function that returns the maximum possible
// profit from given array of jobs
int findMaxProfit(Job arr[], int n)
{
    // Sort jobs according to finish time
    sort(arr, arr+n, jobComparator);
 
    return findMaxProfitRec(arr, n);
}
 
// Driver program
int main()
{
    Job arr[] = {{3, 10, 20}, {1, 2, 50}, {6, 19, 100}, {2, 100, 200}};
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << "The optimal profit is " << findMaxProfit(arr, n);
    return 0;
}


Java




// JAVA program for weighted job scheduling using Naive Recursive Method
import java.util.*;
class GFG
{
   
// A job has start time, finish time and profit.
static class Job
{
    int start, finish, profit;
    Job(int start, int finish, int profit)
     {
        this.start = start;
        this.finish = finish;
        this.profit = profit;
     }
}
 
// Find the latest job (in sorted array) that doesn't
// conflict with the job[i]. If there is no compatible job,
// then it returns -1.
static int latestNonConflict(Job arr[], int i)
{
    for (int j = i - 1; j >= 0; j--)
    {
        if (arr[j].finish <= arr[i - 1].start)
            return j;
    }
    return -1;
}
 
// A recursive function that returns the maximum possible
// profit from given array of jobs. The array of jobs must
// be sorted according to finish time.
static int findMaxProfitRec(Job arr[], int n)
{
    // Base case
    if (n == 1) return arr[n-1].profit;
 
    // Find profit when current job is included
    int inclProf = arr[n-1].profit;
    int i = latestNonConflict(arr, n);
    if (i != -1)
    inclProf += findMaxProfitRec(arr, i+1);
 
    // Find profit when current job is excluded
    int exclProf = findMaxProfitRec(arr, n-1);
 
    return Math.max(inclProf, exclProf);
}
 
// The main function that returns the maximum possible
// profit from given array of jobs
static int findMaxProfit(Job arr[], int n)
{
    // Sort jobs according to finish time
    Arrays.sort(arr,new Comparator<Job>(){
       public int compare(Job j1,Job j2)
        {
           return j1.finish-j2.finish;
        }
       });
 
    return findMaxProfitRec(arr, n);
}
 
// Driver program
public static void main(String args[])
{
   int m = 4;
   Job arr[] = new Job[m];
    arr[0] = new Job(3, 10, 20);
    arr[1] = new Job(1, 2, 50);
    arr[2] = new Job(6, 19, 100);
    arr[3] = new Job(2, 100, 200);
    int n =arr.length;
    System.out.println("The optimal profit is " + findMaxProfit(arr, n));
}
}
 
// This code is contributed by Debojyoti Mandal


Python3




# Python3 program for weighted job scheduling using
# Naive Recursive Method
 
# Importing the following module to sort array
# based on our custom comparison function
from functools import cmp_to_key
 
# A job has start time, finish time and profit
class Job:
     
    def __init__(self, start, finish, profit):
         
        self.start = start
        self.finish = finish
        self.profit = profit
 
# A utility function that is used for
# sorting events according to finish time
def jobComparator(s1, s2):
     
    return s1.finish < s2.finish
 
# Find the latest job (in sorted array) that
# doesn't conflict with the job[i]. If there
# is no compatible job, then it returns -1
def latestNonConflict(arr, i):
     
    for j in range(i - 1, -1, -1):
        if arr[j].finish <= arr[i - 1].start:
            return j
             
    return -1
 
# A recursive function that returns the
# maximum possible profit from given
# array of jobs. The array of jobs must
# be sorted according to finish time
def findMaxProfitRec(arr, n):
     
    # Base case
    if n == 1:
        return arr[n - 1].profit
 
    # Find profit when current job is included
    inclProf = arr[n - 1].profit
    i = latestNonConflict(arr, n)
     
    if i != -1:
        inclProf += findMaxProfitRec(arr, i + 1)
 
    # Find profit when current job is excluded
    exclProf = findMaxProfitRec(arr, n - 1)
    return max(inclProf, exclProf)
 
# The main function that returns the maximum
# possible profit from given array of jobs
def findMaxProfit(arr, n):
     
    # Sort jobs according to finish time
    arr = sorted(arr, key = cmp_to_key(jobComparator))
    return findMaxProfitRec(arr, n)
 
# Driver code
values = [ (3, 10, 20), (1, 2, 50),
           (6, 19, 100), (2, 100, 200) ]
arr = []
for i in values:
    arr.append(Job(i[0], i[1], i[2]))
     
n = len(arr)
 
print("The optimal profit is", findMaxProfit(arr, n))
 
# This code is code contributed by Kevin Joshi


Javascript




<script>
 
// JavaScript program for weighted job scheduling using
// Naive Recursive Method
 
// A job has start time, finish time and profit
class Job
{
    constructor(start, finish, profit)
    {
        this.start = start
        this.finish = finish
        this.profit = profit
    }
}
 
// A utility function that is used for
// sorting events according to finish time
function jobComparator(s1, s2){
     
    return s2.finish - s1.finish;
}
 
// Find the latest job (in sorted array) that
// doesn't conflict with the job[i]. If there
// is no compatible job, then it returns -1
function latestNonConflict(arr, i){
     
    for(let j = i - 1; j >= 0; j--)
    {
        if(arr[j].finish <= arr[i - 1].start)
            return j
    }       
    return -1
}
 
// A recursive function that returns the
// maximum possible profit from given
// array of jobs. The array of jobs must
// be sorted according to finish time
function findMaxProfitRec(arr, n){
     
    // Base case
    if(n == 1)
        return arr[n - 1].profit
 
    // Find profit when current job is included
    let inclProf = arr[n - 1].profit
    let i = latestNonConflict(arr, n)
     
    if(i != -1)
        inclProf += findMaxProfitRec(arr, i + 1)
 
    // Find profit when current job is excluded
    let exclProf = findMaxProfitRec(arr, n - 1)
    return Math.max(inclProf, exclProf)
}
 
// The main function that returns the maximum
// possible profit from given array of jobs
function findMaxProfit(arr, n){
     
    // Sort jobs according to finish time
    arr.sort(jobComparator)
    return findMaxProfitRec(arr, n)
 
}
 
// Driver code
let values = [ [3, 10, 20], [1, 2, 50],
           [6, 19, 100], [2, 100, 200] ]
let arr = []
for(let i of values)
    arr.push(new Job(i[0], i[1], i[2]))
     
let n = arr.length
document.write("The optimal profit is ", findMaxProfit(arr, n),"</br>")
 
// This code is code contributed by shinjanpatra
 
</script>


Output: 

The optimal profit is 250

The above solution may contain many overlapping subproblems. For example, if lastNonConflicting() always returns the previous job, then findMaxProfitRec(arr, n-1) is called twice and the time complexity becomes O(n*2n). As another example when lastNonConflicting() returns previous to the previous job, there are two recursive calls, for n-2 and n-1. In this example case, recursion becomes the same as Fibonacci Numbers. 

So this problem has both properties of Dynamic Programming, Optimal Substructure, and Overlapping Subproblems. 
Like other Dynamic Programming Problems, we can solve this problem by making a table that stores solutions of subproblems.

Below is an implementation based on Dynamic Programming. 

C++




// C++ program for weighted job scheduling using Dynamic
// Programming.
#include <algorithm>
#include <iostream>
using namespace std;
 
// A job has start time, finish time and profit.
struct Job {
    int start, finish, profit;
};
 
// A utility function that is used for sorting events
// according to finish time
bool jobComparator(Job s1, Job s2)
{
    return (s1.finish < s2.finish);
}
 
// Find the latest job (in sorted array) that doesn't
// conflict with the job[i]
int latestNonConflict(Job arr[], int i)
{
    for (int j = i - 1; j >= 0; j--) {
        if (arr[j].finish <= arr[i].start)
            return j;
    }
    return -1;
}
 
// The main function that returns the maximum possible
// profit from given array of jobs
int findMaxProfit(Job arr[], int n)
{
    // Sort jobs according to finish time
    sort(arr, arr + n, jobComparator);
 
    // Create an array to store solutions of subproblems.
    // table[i] stores the profit for jobs till arr[i]
    // (including arr[i])
    int* table = new int[n];
    table[0] = arr[0].profit;
 
    // Fill entries in M[] using recursive property
    for (int i = 1; i < n; i++) {
        // Find profit including the current job
        int inclProf = arr[i].profit;
        int l = latestNonConflict(arr, i);
        if (l != -1)
            inclProf += table[l];
 
        // Store maximum of including and excluding
        table[i] = max(inclProf, table[i - 1]);
    }
 
    // Store result and free dynamic memory allocated for
    // table[]
    int result = table[n - 1];
    delete[] table;
 
    return result;
}
 
// Driver program
int main()
{
    Job arr[] = { { 3, 10, 20 },
                  { 1, 2, 50 },
                  { 6, 19, 100 },
                  { 2, 100, 200 } };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "The optimal profit is "
         << findMaxProfit(arr, n);
    return 0;
}


Java




// JAVA program for weighted job scheduling using Naive
// Recursive Method
import java.util.*;
class GFG {
 
    // A job has start time, finish time and profit.
    static class Job {
        int start, finish, profit;
        Job(int start, int finish, int profit)
        {
            this.start = start;
            this.finish = finish;
            this.profit = profit;
        }
    }
 
    // Find the latest job (in sorted array) that doesn't
    // conflict with the job[i]. If there is no compatible
    // job, then it returns -1.
    static int latestNonConflict(Job arr[], int i)
    {
        for (int j = i - 1; j >= 0; j--) {
            // finish before next is started
            if (arr[j].finish <= arr[i - 1].start)
                return j;
        }
        return -1;
    }
 
    static int findMaxProfitDP(Job arr[], int n)
    {
 
        // Create an array to store solutions of
        // subproblems.  table[i] stores the profit for jobs
        // till arr[i] (including arr[i])
        int[] table = new int[n];
        table[0] = arr[0].profit;
 
        // Fill entries in M[] using recursive property
        for (int i = 1; i < n; i++) {
            // Find profit including the current job
            int inclProf = arr[i].profit;
            int l = latestNonConflict(arr, i);
            if (l != -1)
                inclProf += table[l];
 
            // Store maximum of including and excluding
            table[i] = Math.max(inclProf, table[i - 1]);
        }
 
        // Store result and free dynamic memory allocated
        // for table[]
        int result = table[n - 1];
 
        return result;
    }
 
    // The main function that returns the maximum possible
    // profit from given array of jobs
    static int findMaxProfit(Job arr[], int n)
    {
        // Sort jobs according to finish time
        Arrays.sort(arr, new Comparator<Job>() {
            public int compare(Job j1, Job j2)
            {
                return j1.finish - j2.finish;
            }
        });
 
        return findMaxProfitDP(arr, n);
    }
 
    // Driver program
    public static void main(String args[])
    {
        int m = 4;
        Job arr[] = new Job[m];
        arr[0] = new Job(3, 10, 20);
        arr[1] = new Job(1, 2, 50);
        arr[2] = new Job(6, 19, 100);
        arr[3] = new Job(2, 100, 200);
        int n = arr.length;
        System.out.println("The optimal profit is "
                           + findMaxProfit(arr, n));
    }
}


Python3




# Python3 program for weighted job scheduling
# using Dynamic Programming
 
# Importing the following module to sort array
# based on our custom comparison function
from functools import cmp_to_key
 
# A job has start time, finish time and profit
 
 
class Job:
 
    def __init__(self, start, finish, profit):
 
        self.start = start
        self.finish = finish
        self.profit = profit
 
# A utility function that is used for sorting
# events according to finish time
 
 
def jobComparator(s1, s2):
 
    return s1.finish < s2.finish
 
# Find the latest job (in sorted array) that
# doesn't conflict with the job[i]. If there
# is no compatible job, then it returns -1
 
 
def latestNonConflict(arr, i):
 
    for j in range(i - 1, -1, -1):
        if arr[j].finish <= arr[i - 1].start:
            return j
 
    return -1
 
# The main function that returns the maximum possible
# profit from given array of jobs
 
 
def findMaxProfit(arr, n):
 
    # Sort jobs according to finish time
    arr = sorted(arr, key=cmp_to_key(jobComparator))
 
    # Create an array to store solutions of subproblems.
    # table[i] stores the profit for jobs till arr[i]
    # (including arr[i])
    table = [None] * n
    table[0] = arr[0].profit
 
    # Fill entries in M[] using recursive property
    for i in range(1, n):
 
        # Find profit including the current job
        inclProf = arr[i].profit
        l = latestNonConflict(arr, i)
 
        if l != -1:
            inclProf += table[l]
 
        # Store maximum of including and excluding
        table[i] = max(inclProf, table[i - 1])
 
    # Store result and free dynamic memory
    # allocated for table[]
    result = table[n - 1]
 
    return result
 
 
# Driver code
values = [(3, 10, 20), (1, 2, 50),
          (6, 19, 100), (2, 100, 200)]
arr = []
for i in values:
    arr.append(Job(i[0], i[1], i[2]))
 
n = len(arr)
 
print("The optimal profit is", findMaxProfit(arr, n))
 
# This code is contributed by Kevin Joshi


Javascript




<script>
 
// JavaScript program for weighted job scheduling using
// Naive Recursive Method
 
// A job has start time, finish time and profit
class Job{
     
    constructor(start, finish, profit){
         
        this.start = start
        this.finish = finish
        this.profit = profit
    }
 
}
 
// A utility function that is used for
// sorting events according to finish time
function jobComparator(s1, s2){
     
    return s1.finish - s2.finish
}
 
// Find the latest job (in sorted array) that
// doesn't conflict with the job[i]. If there
// is no compatible job, then it returns -1
function latestNonConflict(arr, i){
     
    for(let j=i-1;j>=0;j--){
        if (arr[j].finish <= arr[i - 1].start)
            return j
    }
             
    return -1
}
 
 
// The main function that returns the maximum
// possible profit from given array of jobs
function findMaxProfit(arr, n){
     
    // Sort jobs according to finish time
    arr.sort(jobComparator)
 
    // Create an array to store solutions of subproblems.
    // table[i] stores the profit for jobs till arr[i]
    // (including arr[i])
    let table = new Array(n).fill(null)
    table[0] = arr[0].profit
 
    // Fill entries in M[] using recursive property
    for(let i=1;i<n;i++){
 
        // Find profit including the current job
        let inclProf = arr[i].profit
        let l = latestNonConflict(arr, i)
 
        if (l != -1)
            inclProf += table[l]
 
        // Store maximum of including and excluding
        table[i] = Math.max(inclProf, table[i - 1])
     
    }
 
    // Store result and free dynamic memory
    // allocated for table[]
    let result = table[n - 1]
 
    return result
}
 
// Driver code
let values = [ [3, 10, 20], [1, 2, 50], [6, 19, 100], [2, 100, 200] ]
let arr = []
for(let i of values)
    arr.push(new Job(i[0], i[1], i[2]))
     
let n = arr.length
 
document.write("The optimal profit is ", findMaxProfit(arr, n),"</br>")
 
// This code is code contributed by shinjanpatra
 
</script>


Output: 

The optimal profit is 250

Time Complexity of the above Dynamic Programming Solution is O(n2). Note that the above solution can be optimized to O(nLogn) using Binary Search in latestNonConflict() instead of linear search. Thanks to Garvit for suggesting this optimization. Please refer below post for details.

Weighted Job Scheduling in O(n Log n) time

References: 
http://courses.cs.washington.edu/courses/cse521/13wi/slides/06dp-sched.pdf

 



Previous Article
Next Article

Similar Reads

Weighted Job Scheduling in O(n Log n) time
Given N jobs where every job is represented by following three elements of it. Start TimeFinish TimeProfit or Value Associated Find the maximum profit subset of jobs such that no two jobs in the subset overlap.Example: Input: Number of Jobs n = 4 Job Details {Start Time, Finish Time, Profit} Job 1: {1, 2, 50} Job 2: {3, 5, 20} Job 3: {6, 19, 100} J
11 min read
Find Jobs involved in Weighted Job Scheduling
Given N jobs where every job is represented by following three elements of it.1. Start Time 2. Finish Time 3. Profit or Value AssociatedFind the subset of jobs associated with maximum profit such that no two jobs in the subset overlap. Examples: Input: Number of Jobs n = 4 Job Details {Start Time, Finish Time, Profit} Job 1: {1, 2, 50} Job 2: {3, 5
11 min read
Weighted Job Scheduling | Set 2 (Using LIS)
Given N jobs where every job is represented by following three elements of it.1. Start Time 2. Finish Time 3. Profit or Value AssociatedFind the maximum profit subset of jobs such that no two jobs in the subset overlap. Examples: Input: Number of Jobs n = 4 Job Details {Start Time, Finish Time, Profit} Job 1: {1, 2, 50} Job 2: {3, 5, 20} Job 3: {6,
10 min read
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
The shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting process with the smallest execution time to execute next. SJN, also known as Shortest Job Next (SJN), can be preemptive or non-preemptive. Characteristics of SJF Scheduling: Shortest Job first has the advantage of having a minimum average waiting time
13 min read
Job Scheduling with two jobs allowed at a time
We are given N jobs, and their starting and ending times. We can do two jobs simultaneously at a particular moment. If one job ends at the same moment some other show starts then we can't do them. We need to check if it is possible to complete all the jobs or not.Examples: Input : Start and End times of Jobs 1 2 2 3 4 5 Output : Yes By the time thi
7 min read
Shortest Job First (or SJF) CPU Scheduling Non-preemptive algorithm using Segment Tree
Shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting process with the smallest execution time to execute next. SJN is a non-preemptive algorithm.   Shortest Job first has the advantage of having a minimum average waiting time among all scheduling algorithms.It is a Greedy Algorithm.It may cause starvation i
15+ min read
Implementation of Shortest Job First (SJF) Scheduling in Python
Shortest Job First (SJF) scheduling is a non-preemptive CPU scheduling algorithm where the process with the smallest burst time is selected for execution from the ready queue. The objective is to minimize the average waiting time of processes. Example 1: Consider the following processes with their burst times: ProcessBurst TimeP16P28P37P43Output: A
2 min read
Sum of count of persons still performing the job whenever a person finishes job
Given two integers P denoting the number of people and a positive integer K. Each person is assigned with the same job which takes exactly K hours to finish. A condition is given that all of them can start performing their jobs exactly in X hours of interval. Count the number of persons still performing the job whenever a prior person finishes his/
6 min read
Shortest path with exactly k edges in a directed and weighted graph
Given a directed and two vertices ‘u’ and ‘v’ in it, find shortest path from ‘u’ to ‘v’ with exactly k edges on the path. The graph is given as adjacency matrix representation where value of graph[i][j] indicates the weight of an edge from vertex i to vertex j and a value INF(infinite) indicates no edge from i to j. For example, consider the follow
15+ min read
Probability of a random pair being the maximum weighted pair
Given two arrays A and B, a random pair is picked having an element from array A and another from array B. Output the probability of the pair being maximum weighted. Examples: Input : A[] = 1 2 3 B[] = 1 3 3 Output : 0.222 Explanation : Possible pairs are : {1, 1}, {1, 3}, {1, 3}, {2, 1}, {2, 3}, {2, 3}, {3, 1}, {3, 3}, {3, 3} i.e. 9. The pair with
7 min read
Find the root of the sub-tree whose weighted sum XOR with X is maximum
Given a tree, and the weights of all the nodes, the task is to find the root of the sub-tree whose weighted sum XOR with given integer X is maximum.Examples: Input: X = 15 Output: 4 Weight of sub-tree for parent 1 = ((-1) + (5) + (-2) + (-1) + (3)) XOR 15 = 4 XOR 15 = 11 Weight of sub-tree for parent 2 = ((5) + (-1) + (3)) XOR 15 = 7 XOR 15 = 8 Wei
7 min read
Weighted sum of the characters of a string in an array | Set 2
You are given an array of strings str[], the task is to find the score of a given string s from the array. The score of a string is defined as the product of the sum of its characters’ alphabetical values with the position of the string in the array. Examples: Input: str[] = {"sahil", "shashanak", "sanjit", "abhinav", "mohit"}, s = "abhinav" Output
10 min read
Find the root of the sub-tree whose weighted sum is minimum
Given a tree, and the weights of all the nodes, the task is to find the root of the sub-tree whose weighted sum is minimum. Examples: Input: Output: 5 Weight of sub-tree for parent 1 = ((-1) + (5) + (-2) + (-1) + (3)) = 4 Weight of sub-tree for parent 2 = ((5) + (-1) + (3)) = 7 Weight of sub-tree for parent 3 = -1 Weight of sub-tree for parent 4 =
7 min read
Find the root of the sub-tree whose weighted sum XOR with X is minimum
Given a tree, and the weights of all the nodes, the task is to find the root of the sub-tree whose weighted sum XOR with given integer X is minimum.Examples: Input: X = 15 Output: 5 Weight of sub-tree for parent 1 = ((-1) + (5) + (-2) + (-1) + (3)) XOR 15 = 4 XOR 15 = 11 Weight of sub-tree for parent 2 = ((5) + (-1) + (3)) XOR 15 = 7 XOR 15 = 8 Wei
7 min read
Count the nodes of the tree whose weighted string contains a vowel
Given a tree, and the weights (in the form of strings) of all the nodes, the task is to count the nodes whose weights contain a vowel. Examples: Input: Output: 2 Only the strings of the nodes 1 and 5 contain vowels. Approach: Perform dfs on the tree and for every node, check if it's string contains vowels, If yes then increment the count. Below is
7 min read
Count the nodes of a tree whose weighted string does not contain any duplicate characters
Given a tree, and the weights (in the form of strings) of all the nodes, the task is to count the nodes whose weights do not contain any duplicate character.Examples: Input: Output: 2 Only the strings of the node 1 and 4 contains unique strings. Approach: Perform dfs on the tree and for every node, check if its string contains duplicate char or not
5 min read
Count the nodes of a tree whose weighted string is an anagram of the given string
Given a tree, and the weights (in the form of strings) of all the nodes, the task is to count the nodes whose weighted string is an anagram with the given string str.Examples: Input: str = "geek" Output: 2 Only the weighted strings of the nodes 2 and 6 are anagrams of the given string "geek". Approach: Perform dfs on the tree and for every node, ch
6 min read
Minimum distance to visit all the nodes of an undirected weighted tree
Given a weighted tree with N nodes starting from 1 to N. The distance between any two nodes is given by the edge weight. Node 1 is the source, the task is to visit all the nodes of the tree with the minimum distance traveled. Examples: Input: u[] = {1, 1, 2, 2, 1} v[] = {2, 3, 5, 6, 4} w[] = {1, 4, 2, 50, 5} Output: 73 Input: u[] = {1, 2} v[] = {2,
10 min read
Shortest path with exactly k edges in a directed and weighted graph | Set 2
Given a directed weighted graph and two vertices S and D in it, the task is to find the shortest path from S to D with exactly K edges on the path. If no such path exists, print -1. Examples: Input: N = 3, K = 2, ed = {{{1, 2}, 5}, {{2, 3}, 3}, {{3, 1}, 4}}, S = 1, D = 3 Output: 8 Explanation: The shortest path with two edges will be 1->2->3
8 min read
Weighted Sum Method - Multi Criteria Decision Making
Weighted Sum Method is a multi-criterion decision-making method in which there will be multiple alternatives and we have to determine the best alternative based on multiple criteria. There are other methods available including Weighted Product Method (WPM), Technique for Order of Preference by Similarity to Ideal Solution (TOPSIS), VIKOR, MOORA, GT
3 min read
Minimum Cost of Simple Path between two nodes in a Directed and Weighted Graph
Given a directed graph, which may contain cycles, where every edge has weight, the task is to find the minimum cost of any simple path from a given source vertex ‘s’ to a given destination vertex ‘t’. Simple Path is the path from one vertex to another such that no vertex is visited more than once. If there is no simple path possible then return INF
10 min read
Count of leaf nodes of the tree whose weighted string is a palindrome
Given an N-ary tree, and the weights which are in the form of strings of all the nodes, the task is to count the number of leaf nodes whose weights are palindrome. Examples: Input: 1(ab) / \ (abca)2 5 (aba) / \ (axxa)3 4 (geeks) Output: 2 Explanation: Only the weights of the leaf nodes "axxa" and "aba" are palindromes. Input: 1(abx) / 2(abaa) / 3(a
7 min read
Minimum difference between any two weighted nodes in Sum Tree of the given Tree
Given a tree of N nodes, the task is to convert the given tree to its Sum Tree(including its own weight) and find the minimum difference between any two node's weight of the sum tree. Note: The N nodes of the given tree are given in the form of top to bottom with N-1 line where each line describes two nodes that are connected. Examples: Input: Outp
11 min read
Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
Given an N-ary tree with weighted edge and Q queries where each query contains two nodes of the tree. The task is to find the maximum weighted edge in the simple path between these two nodes.Examples: Naive Approach: A simple solution is to traverse the whole tree for each query and find the path between the two nodes.Efficient Approach: The idea i
15 min read
Number of spanning trees of a weighted complete Graph
Prerequisites: Graph Theory Basics, Spanning tree. Complete Weighted Graph: A graph in which an edge connects each pair of graph vertices and each edge has a weight associated with it is known as a complete weighted graph. The number of spanning trees for a complete weighted graph with n vertices is n(n-2). Proof: Spanning tree is the subgraph of g
4 min read
Queries to find sum of distance of a given node to every leaf node in a Weighted Tree
Given a Undirected Weighted Tree having N nodes and E edges. Given Q queries, with each query indicating a starting node. The task is to print the sum of the distances from a given starting node S to every leaf node in the Weighted Tree.Examples: Input: N = 5, E = 4, Q = 3 1 (4) / \ (2) / \ 4 2 (5)/ \ (3) / \ 5 3Query 1: S = 1 Query 2: S = 3 Query
15 min read
Program to find weighted median of a given array
Given two arrays arr[] of N integers and W[] of N weights where W[i] is the weight for the element arr[i]. The task is to find the weighted median of the given array. Note: The sum of the weight of all elements will always be 1. Let the array arr[] be arranged in increasing order with their corresponding weights. If N is odd, then there is only one
10 min read
Number of shortest paths in an Undirected Weighted Graph
Given a weighted undirected graph G and an integer S, the task is to print the distances of the shortest paths and the count of the number of the shortest paths for each node from a given vertex, S. Examples: Input: S =1, G = Output: Shortest Paths distances are : 0 1 2 4 5 3 2 1 3 Numbers of the shortest Paths are: 1 1 1 2 3 1 1 1 2 Explanation: T
15 min read
In a weighted graph, Is zero allowed as an edge's weight?
In this article, we will discuss the overview of the Graph and will focus on a scenario wherein a weighted graph, Is zero allowed as an edge's weight. Let's discuss it one by one as follows. Overview :A graph is defined as a G(V, E) where V is a set of vertices and E is the set of edges. The interconnected point from one object to another object is
3 min read
Minimum cost of path between given nodes containing at most K nodes in a directed and weighted graph
Given a directed weighted graph represented by a 2-D array graph[][] of size n and 3 integers src, dst, and k representing the source point, destination point, and the available number of stops. The task is to minimize the cost of the path between two nodes containing at most K nodes in a directed and weighted graph. If there is no such route, retu
10 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg