Matrix of given integers a1,1 a1,2 ... a1, n a2,1 a2,2 ... a2, n :: an, 1 an, 2 ... an,…
- User
Matrix of given integers
a1,1 a1,2 ... a1, n a2,1 a2,2 ... a2, n :: an, 1 an, 2 ... an, n
Then, create a program that outputs the maximum value of the sum of one or more consecutive terms (submatrix) in the vertical and horizontal directions and ends. Input
The input data is given in the following format.
n a1,1 a1,2 ... a1, n a2,1 a2,2 ... a2, n :: an, 1 an, 2 ... an, n
n is 1 or more and 100 or less, and ai, j is -10000 or more and 10000 or less.
Output
Print the maximum value on one line.
Examples
Input
3 1 -2 3 -4 5 6 7 8 -9
Output
16
Input
4 1 3 -9 2 2 7 -1 5 -8 3 2 -1 5 0 -3 1
Output
15
Assistant
pythonn = int(input()) matrix = [] for _ in range(n): row = list(map(int, input().split())) matrix.append(row) # Precompute prefix sums for each row prefix = [] for row in matrix: current_prefix = [0] s = 0 for num in row: s += num current_prefix.append(s) prefix.append(current_prefix) max_sum = -float('inf') # Iterate over all possible left and right column pairs for left in range(n): for right in range(left, n): current_sums = [] for i in range(n): sum_row = prefix[i][right + 1] - prefix[i][left] current_sums.append(sum_row) # Apply Kadane's algorithm on current_sums if not current_sums: continue current_max = current_sums[0] max_ending_here = current_sums[0] for num in current_sums[1:]: max_ending_here = max(num, max_ending_here + num) current_max = max(current_max, max_ending_here) if current_max > max_sum: max_sum = current_max print(max_sum)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.