Skip to main content

1235. Maximum Profit in Job Scheduling

Hi everyone, Today's post is little bit intriguing to me as it took me some time to get t the solution. I have been out of practice for a bit so I was not able to do it in the DP. I didn't want to copy the code. Though i understood the code after i checked its solution in the discussions. Anyways, i tried to do it with heap and with some thinking I was able to do it and with my surprise It performed real well.

I would like to jump to the solution but first I would like to explain a little bit about heaps so you can get better understanding of the code.

A heap is like a special type of list where the smallest (or largest) item is always at the front. Think of it like a priority line at a theme park, where the person with the highest priority goes to the front.

There are two types of heaps:

  1. Min Heap:

    • The smallest item is at the front.
    • It's like standing in a line where the shortest person is always at the front.
  2. Max Heap:

    • The largest item is at the front.
    • It's like standing in a line where the tallest person is always at the front.

In Python, we use the heapq module to work with heaps. Here's a simple example

import heapq

# Create an empty heap
heap = []

# Add some numbers to the heap
heapq.heappush(heap, 4)
heapq.heappush(heap, 1)
heapq.heappush(heap, 7)
heapq.heappush(heap, 3)

# The smallest number is always at the front
smallest = heapq.heappop(heap)

print(smallest) # Output: 1
#Till the second last night where heappop is not done this will be the structure of 
heap

1
/ \
4 7
/
3


#After heapop smallest element will be removed from the heap so it will become

3
/ \
4 7

In this example, heapq.heappush() adds numbers to the heap, and heapq.heappop() takes out the smallest number. It's like letting the person with the highest priority go first in the theme park line.

Heaps are handy because they make it really quick to find and remove the smallest (or largest) item, which is useful in certain types of problems. Just remember, the "priority" is determined by whether it's a min heap (shortest person first) or a max heap (tallest person first).

I will make an entire section for heaps later but for now just know that in heap time complexity of heapify (maintaining heap property), push and pop in O(logN). Finding maximum/minimum takes O(1) time and building a heap has O(N) time complexity.

Now moving on to the solution.

class Solution:
def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
n = len(startTime)
jobs = [[startTime[i], endTime[i], profit[i]] for i in range(n)]
jobs.sort(key=lambda x:x[0])
heap = []
curr_profit, mx_profit = 0, 0

for start, end, profit in jobs:
while heap and heap[0][0]<=start:
end_time, temp = heapq.heappop(heap)
curr_profit = max(curr_profit, temp)
heapq.heappush(heap,(end, curr_profit+profit))
mx_profit = max(mx_profit, curr_profit+profit)
# print(heap)
 
return mx_profit

 in the above code:

        n = len(startTime)
        jobs = [[startTime[i], endTime[i], profit[i]] for i in range(n)] 

  •  We first calculate the number of jobs (n) based on the length of the startTime list. Then, it creates a list of jobs (jobs) by combining the corresponding elements of startTime, endTime, and profit using a list comprehension

    jobs.sort(key=lambda x: x[0])

  • The jobs list is sorted based on the start times of the jobs. This sorting is essential for the subsequent steps, as it allows the algorithm to process the jobs in chronological order.

    heap = []
    curr_profit, mx_profit = 0, 0

  • Here, an empty heap (heap) is initialized, and two variables curr_profit and mx_profit are set to 0. curr_profit is used to keep track of the current profit during the iteration, and mx_profit stores the maximum profit obtained so far.

            for start, end, profit in jobs:
                while heap and heap[0][0] <= start:
                    end_time, temp = heapq.heappop(heap)
                    curr_profit = max(curr_profit, temp)
                heapq.heappush(heap, (end, curr_profit + profit))
                mx_profit = max(mx_profit, curr_profit + profit)
     

    This is where the entire magic happens.

    The main loop iterates through the sorted jobs list. For each job, it checks the heap to find jobs that have already finished (end time is less than or equal to the current job's start time). It pops such jobs from the heap and updates the curr_profit variable accordingly.

    Then, it pushes the current job onto the heap, considering the updated profit. The mx_profit variable is updated to keep track of the maximum profit obtained so far.

     

    In the end we return the mx_profit, giving us the correct answer.

    Performance of the code:

     

    Time complexity - O(nlogn)

    The dominant factor in the time complexity is the sorting of the jobs list, which takes O(n log n) time, where 'n' is the number of jobs. The loop that follows processes each job once, and for each job, it may involve operations like pushing and popping from the heap (logarithmic time in the size of the heap). Therefore, the overall time complexity is O(n log n).

    Space Complexity - O(N)

    We have to create `jobs` and `heap` array and heap structure so it takes N space to store the info about each job.

     

    I hope you like this. If you need any other code solution to be explained do let me know in the comments. Happy coding :)

 

Comments

Post a Comment

Popular posts from this blog

WhatsApp hidden Fonts

WhatsApp is a messaging app used by over 1 million world wide. It have been the default messaging app for the people since it was first made, Social messaging app supports Android, IOS and windows. It surely have become crucial part of our lives but some of us may not know about some of its hidden features. Whatsapp gives its user full liberty to block useless contacts, choose wisely to let other people know whether you read their messages or not (read receipts), setting privacy, secret fonts, and recent updates gave us the option to post stories too, no doubt why it is number 1 messaging app. Some of us may know the feature of hidden text and some of us may not, they are very simple. If you ever wanted to highlight the particular text or say make it bold so you can do that on whatsapp Here are some cool tricks that you can do while typing messages to your friends. Italicize the text by placing asterisks before and after the text. _techgen_ make the text appear bold by placing tidle sy...

What is a Processor?

Smartphones have been the most important part of our lives. We have seen the evolution of our  handsets. First we saw landlines which were mess of tangled wires then we saw mobile phones which is successor of landlines. They were portable devices from which you can make calls then we witnessed emergence of Smartphones which were  considered as portable computers which also allows us to make calls. What is a Processor? Underneath that touchscreen display there is a full- fledged computer that commands your apps so that they function properly. A processor executes what you want your smartphone to do or in other word you can say processor is brain of computer. there is Exynos, Snapdragon, quad-core octa-core etc. What is a core? It is an element of surprises. They are present inside processor and are responsible for reading the command and executing them. First devices came with single core processor but later on scientists invented more advanced processors such as dual core , So...

Samsung launches CFG70 curved gaming monitors in India.

Samsung electronics launched its two gaming monitors in India on Thursday, LC24FG70 (24 inch) and LC27FG70 (27 inch)-priced at ₹ 35000 and ₹ 42000 respectively. The company claims that they are first curved gaming computer with a 1 millisecond moving picture response time (MPRT). These two monitors are part of CFG70 series of curved gaming computers which were launched in IFA 2016. Apart from ther fast response time with their VA panels, the both come with Quantum dot technologyand a 144 Hz refresh rate that is optimised for AMD's FreeSynch technology. Both the monitors support a full HD resolution, and company is touting a contrast ratio of 3000:1.Samsung is also boasting of a UX that's specially designed for gamers, with an "intuitive settings dashboard" as well as hotkeys on the front and back of the display to quickly adjust settings between presets. The company also says each monitor undergoes rigorous pre-shipment factory calibration for compatibility with vario...