S2Q2 · Row with Maximum Sum¶
⚡ Quick Reference
Type: Full I/O problem
Core idea: Read the matrix, compute row sums, find the max, then use list.index() to get the first occurrence.
m, n = map(int, input().split())
rows = [list(map(int, input().split())) for _ in range(m)]
sums = [sum(row) for row in rows]
max_sum = max(sums)
print(sums.index(max_sum))
print(max_sum)
Key rules:
- Output is two lines: index first, then sum
- list.index() returns the first occurrence automatically
- Row indices are 0-based
Problem Statement¶
Problem
Read an m × n integer matrix. Print the 0-based index of the row with the maximum sum, followed by that maximum sum. If multiple rows tie, print the index of the first one.
Example:
3 4
1 2 3 4
5 5 5 5
2 2 2 2
1
20
2 3
3 3 3
3 3 3
0
9
Understanding the problem¶
For the first example:
| Row index | Values | Sum |
|---|---|---|
| 0 | 1 2 3 4 |
10 |
| 1 | 5 5 5 5 |
20 ← max |
| 2 | 2 2 2 2 |
8 |
Output: index 1, sum 20.
list.index() always returns the first match
sums.index(max_sum) scans left to right and stops at the first element equal to max_sum. This handles the tie-breaking rule for free -- no need to track the index manually or write extra logic.
Separate max() and index() instead of argmax
Python has no built-in argmax. The clean pattern is: compute max_sum = max(sums), then find where it lives with sums.index(max_sum). Avoid iterating manually with a running max and index variable -- the two-liner above is clearer and less error-prone.
Solution approaches¶
m, n = map(int, input().split())
# Read the matrix
rows = []
for _ in range(m):
row = list(map(int, input().split()))
rows.append(row)
# Compute row sums
sums = [sum(row) for row in rows]
# Find max and its first index
max_sum = max(sums)
max_idx = sums.index(max_sum) # first occurrence
print(max_idx)
print(max_sum)
Key takeaways¶
list.index() for first-occurrence lookup
sums.index(max_sum) scans left to right and returns the index of the first element equal to max_sum. This gives the tie-breaking "first row wins" rule for free -- no extra conditional logic needed.
Reading a matrix with a list comprehension
[list(map(int, input().split())) for _ in range(m)] reads all rows in one expression. Each input().split() gives string tokens; map(int, ...) converts them to integers; list() materialises the result.
Skipping storage when only sums are needed
The Pythonic version computes sum(...) on each row as it is read, storing only the sums list rather than the full matrix. For large inputs this halves memory usage -- the original rows are discarded immediately.