Job Sequencing

PHOTO EMBED

Mon Nov 18 2024 17:28:37 GMT+0000 (Coordinated Universal Time)

Saved by @hi123

import java.util.*; 
 
class Job { 
    private int id; 
    private int deadline; 
    private int profit; 
 
    Job(int id, int deadline, int profit) { 
        this.id = id; 
        this.deadline = deadline; 
        this.profit = profit; 
    } 
 
    public int getId() { 
        return id; 
    } 
 
    public int getDeadline() { 
        return deadline; 
    } 
 
    public int getProfit() { 
        return profit; 
    } 
} 
 
public class JobSeq { 
    public static void main(String[] args) { 
        Scanner scan = new Scanner(System.in); 
        System.out.println("enter no of jobs"); 
        int n = scan.nextInt(); 
        Job[] jobs = new Job[n]; 
        System.out.println("emter job id,deadline,profit"); 
        for (int i = 0; i < n; i++) { 
            jobs[i] = new Job(scan.nextInt(), scan.nextInt(), scan.nextInt()); 
        } 
        js(jobs); 
    } 
 
    public static void js(Job[] jobs) { 
        Arrays.sort(jobs, new Comparator<Job>() { 
            public int compare(Job j1, Job j2) { 
                return j2.getProfit() - j1.getProfit(); 
            } 
        }); 
 
        int maxDeadline = 0; 
        for (Job job : jobs) { 
            if (job.getDeadline() > maxDeadline) { 
                maxDeadline = job.getDeadline(); 
            } 
        } 
 
        Job[] result = new Job[maxDeadline]; 
        boolean[] slot = new boolean[maxDeadline]; 
 
        for (Job job : jobs) { 
            for (int j = Math.min(maxDeadline, job.getDeadline()) - 1; j >= 0; j--) { 
                if (!slot[j]) { // If the slot is free 
                    result[j] = job; 
                    slot[j] = true; 
                    break; 
                } 
            } 
        } 
 
        int totalProfit = 0; 
        System.out.println("Scheduled jobs:"); 
        for (Job job : result) { 
            if (job != null) { 
                System.out.println("Job ID: " + job.getId() + ", Profit: " + job.getProfit()); 
                totalProfit += job.getProfit(); 
            } 
        } 
        System.out.println("Total profit: " + totalProfit); 
    } 
 
} 
content_copyCOPY