Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find minimum space plane required for skydivers in k days in python
Suppose we have a list of numbers called nums where each value represents a group of people looking to skydive together. And we have another value k representing how many days they can apply for skydiving. We have to find the minimum capacity of the plane we need to be able to fulfill all requests within k days. The requests should be fulfilled in the order they were given and a plane can only fly once a day.
So, if the input is like nums = [16, 12, 18, 11, 13], k = 3, then the output will be 28, as a 28-person airplane can group the given requests by [16, 12], [18], [11, 13].
Algorithm
To solve this, we will follow these steps ?
- If
numsis empty, return 0 -
start:= maximum ofnums,end:= sum of all elements ofnums - While
start < end, do:-
mid:=(start + end) // 2 -
days:= 1,temp:= 0 - For each
numinnums, do:- If
temp + num > mid, then:-
days:=days + 1 -
temp:=num
-
- Otherwise:
-
temp:=temp + num
-
- If
- If
days > k, thenstart:=mid + 1 - Otherwise,
end:=mid
-
- Return
start
Example
class Solution:
def solve(self, nums, k):
if not nums:
return 0
start, end = max(nums), sum(nums)
while start < end:
mid = (start + end) // 2
days = 1
temp = 0
for num in nums:
if temp + num > mid:
days += 1
temp = num
else:
temp += num
if days > k:
start = mid + 1
else:
end = mid
return start
# Test the solution
ob = Solution()
nums = [16, 12, 18, 11, 13]
k = 3
print(ob.solve(nums, k))
28
How It Works
This solution uses binary search to find the minimum plane capacity. The search space ranges from the maximum single group size (minimum possible capacity) to the sum of all groups (maximum possible capacity). For each candidate capacity, we simulate the grouping process to count how many days are needed.
In the example, with capacity 28:
- Day 1: Groups [16, 12] = 28 people (exactly fits)
- Day 2: Group [18] = 18 people
- Day 3: Groups [11, 13] = 24 people
Conclusion
This binary search approach efficiently finds the minimum plane capacity needed to transport all skydivers within the given time constraint. The time complexity is O(n log(sum)) where n is the number of groups.
