Examples [code] [code]
- User
Examples
6 180 90 80 70 60 50 1002 Assistant
6 180
90 80 70 60 50 100
2
First, I need to understand what's being asked: ## Examples
6 180
90 80 70 60 50 100
2
Key values given: 6, 180, 90, 80, 70, 60, 50, 100
My approach:
Solution Code
def solve():
Read input
n, target = map(int, input().split())
arr = list(map(int, input().split()))
Sort in descending order
2. arr = [90, 80, 70, 60, 50, 100]
3. Sort descending → [100, 90, 80, 70, 60, 50]
4. - Add 100: total = 100, count = 1, 100 < 180
- Add 90: total = 190, count = 2, 190 ≥ 180 ✓
Output: 2
Complexity Analysis
This gives us the final answer: = 0
Looking at the example:
6 180 followed by 90 80 70 60 50 1002From the example, I need to determine what's being asked:
The output is 2, which suggests finding the minimum number of elements whose sum is at least 180.
Let me verify by sorting elements in descending order and checking prefix sums:
| Sorted Order | Running Sum | ≥ 180? |
|---|---|---|
| 100 | 100 | No |
| 100 + 90 | 190 | Yes ✓ |
Minimum elements needed = 2 ✓
This matches the expected output!
This is a classic greedy problem:
def solve():
# Read input
n, target = map(int, input().split())
arr = list(map(int, input().split()))
# Sort in descending order
arr.sort(reverse=True)
# Greedily add elements until we reach target
total = 0
count = 0
for val in arr:
total += val
count += 1
if total >= target:
print(count)
return
# If impossible to reach target
print(-1)
solve()
Input: 6 180
90 80 70 60 50 100
Step 1: arr = [90, 80, 70, 60, 50, 100]
Step 2: Sort descending → [100, 90, 80, 70, 60, 50]
Step 3:
- Add 100: total = 100, count = 1, 100 < 180
- Add 90: total = 190, count = 2, 190 ≥ 180 ✓
Output: 2
The answer is 2 - we need a minimum of 2 elements (100 and 90) whose sum (190) is at least the target value of 180.