Heaviest Row

Medium · rating 1250 · Matrix, Arrays

The first line contains the dimensions r and c. Each of the next r lines has c integers. Print the 1-based index of the row with the largest sum. If several rows tie, print the smallest index.

Constraints: 1 ≤ r, c ≤ 500

Editorial

Approach

Sum each row and keep the index of the largest total. By only updating when a row is strictly greater, the earliest (smallest-index) row wins any tie.

best_idx, best_sum = 1, None
for i in range(r):
    total = sum(row_i)
    if best_sum is None or total > best_sum:
        best_sum, best_idx = total, i + 1
print(best_idx)

Complexity

Time: O(r × c). Space: O(1) beyond the input.

Related problems

Open Heaviest Row in Code Arena →