This is a great question about dynamic programming algorithms. Let me break this down into two parts:
- First, solve the maximum subarray problem using Kadane's algorithm
- Then extend it to the maximum submatrix sum problem for an N x N matrix
Part 1: Kadane's Algorithm for Maximum Subarray
Kadane's algorithm works by maintaining:
max_current: the maximum sum ending at the current position
max_global: the overall maximum sum found so far
At each position, we decide whether to:
- Extend the existing subarray (add current element to max_current)
- Start a new subarray from the current position
Part 2: Maximum Submatrix Sum
The key insight is to:
- Fix the top and bottom rows of the submatrix
- Compress the matrix into a 1D array by summing columns between these rows
- Apply Kadane's algorithm to find the maximum sum in this 1D array
- Repeat for all possible pairs of rows
Let me write comprehensive code with examples and explanations:
def maxSubArray(nums):
"""
Kadane's algorithm for maximum subarray sum
Time: O(n), Space: O(1)
"""
max_current = max_global = nums[0]
for i in range(1, len(nums)):
max_current = max(nums[i], max_current + nums[i])
max_global = max(max_global, max_current)
return max_global
def maxSubArray_with_indices(nums):
"""
Kadane's algorithm with subarray indices tracking
Returns: (max_sum, start_index, end_index)
"""
max_current = max_global = nums[0]
start = end = max_start = 0
for i in range(1, len(nums)):
if nums[i] > max_current + nums[i]:
max_current = nums[i]
start = i
else:
max_current += nums[i]
if max_current > max_global:
max_global = max_current
max_start = start
end = i
return max_global, max_start, end
When tracking indices, I need to reset the start position whenever it's better to begin fresh from the current element rather than continuing the previous sum. The algorithm updates the global maximum and its corresponding boundaries whenever a new peak is found.
Now for the 2D version:
def maxSubmatrixSum(matrix):
"""
Maximum submatrix sum using Kadane's algorithm
Time: O(N^3), Space: O(N)
```
I'll iterate through all possible row pairs, collapsing each range into a 1D column sum array, then apply Kadane's algorithm to find the best submatrix. For each top row, I expand downward through every bottom row, accumulating column sums as I go. When I apply Kadane's to the resulting array, I track which columns contain the maximum sum, updating my result whenever I find a better total.
N = len(matrix)
max_sum = float('-inf')
result = {
'max_sum': max_sum,
'top': 0,
'bottom': 0,
'left': 0,
'right': 0
}
for top in range(N):
col_sum = [0] * N
for bottom in range(top, N):
for col in range(N):
col_sum[col] += matrix[bottom][col]
max_left, max_right, current_sum = kadane_1d(col_sum)
if current_sum > max_sum:
max_sum = current_sum
result['max_sum'] = current_sum
result['top'] = top
result['bottom'] = bottom
result['left'] = max_left
result['right'] = max_right
return result
def kadane_1d(arr):
"""
Kadane's algorithm tracking start and end indices of maximum subarray
Returns: (left_index, right_index, max_sum)
"""
max_current = max_global = arr[0]
start = end = max_start = 0
for i in range(1, len(arr)):
if arr[i] > max_current + arr[i]:
max_current = arr[i]
start = i
else:
max_current += arr[i]
if max_current > max_global:
max_global = max_current
max_start = start
end = i
return max_start, end, max_global</think>
# Maximum Subarray & Maximum Submatrix Sum Problem
I'll solve both the 1D problem with Kadane's algorithm and extend it to the 2D maximum submatrix problem.
## Part 1: Kadane's Algorithm (1D)
```python
def max_subarray_kadane(nums):
"""
Find maximum sum of any contiguous subarray using Kadane's algorithm
Time: O(n), Space: O(1)
Key Idea:
- Maintain max_current: max sum ending at current position
- If we should extend: add current element
- If we should restart: start fresh from current element
"""
if not nums:
return 0
max_current = max_global = nums[0]
for i in range(1, len(nums)):
# Either extend the current subarray or start a new one
max_current = max(nums[i], max_current + nums[i])
# Update global maximum
max_global = max(max_global, max_current)
return max_global
def max_subarray_with_details(nums):
"""
Kadane's algorithm with subarray details
Returns: {
'max_sum': int,
'start': int,
'end': int,
'subarray': list
}
"""
if not nums:
return None
max_current = max_global = nums[0]
start = end = max_start = 0
current_start = 0
for i in range(1, len(nums)):
# If starting fresh is better than extending
if nums[i] > max_current + nums[i]:
max_current = nums[i]
current_start = i
else:
max_current += nums[i]
# Update global max
if max_current > max_global:
max_global = max_current
max_start = current_start
end = i
return {
'max_sum': max_global,
'start': max_start,
'end': end,
'subarray': nums[max_start:end+1]
}
# Test Kadane's Algorithm
print("=" * 60)
print("PART 1: KADANE'S ALGORITHM (1D)")
print("=" * 60)
test_cases_1d = [
[-2, 1, -3, 4, -1, 2, 1, -5, 4],
[-1, -2, -3],
[1, 2, 3, 4],
[-2, 11, -4, 13, -5, 2],
[5, -3, 5, -1, 7]
]
for arr in test_cases_1d:
result = max_subarray_with_details(arr)
print(f"\nArray: {arr}")
print(f"Max Sum: {result['max_sum']}")
print(f"Subarray: {result['subarray']} (indices {result['start']}-{result['end']})")
Part 2: Maximum Submatrix Sum (2D) - O(N³)
def max_submatrix_sum(matrix):
"""
Find maximum sum submatrix in N×N matrix using Kadane's algorithm
Time: O(N^3), Space: O(N)
Algorithm:
1. Fix top and bottom rows (O(N^2) combinations)
2. For each pair, collapse to 1D array by summing columns
3. Apply Kadane's algorithm (O(N))
4. Track the best result
Key Insight:
- Reduce 2D problem to multiple 1D problems
- Use Kadane on each column sum between fixed rows
"""
if not matrix:
return None
N = len(matrix)
max_sum = float('-inf')
best_config = {
'max_sum': max_sum,
'top_row': 0,
'bottom_row': 0,
'left_col': 0,
'right_col': 0
}
# Try all pairs of rows
for top_row in range(N):
# Initialize column sum array
col_sum = [0] * N
# Extend down from top_row
for bottom_row in range(top_row, N):
# Add current row to column sum
for col in range(N):
col_sum[col] += matrix[bottom_row][col]
# Apply Kadane's algorithm on col_sum
left_col, right_col, current_sum = kadane_1d_with_indices(col_sum)
# Update best result
if current_sum > max_sum:
max_sum = current_sum
best_config = {
'max_sum': current_sum,
'top_row': top_row,
'bottom_row': bottom_row,
'left_col': left_col,
'right_col': right_col
}
return best_config
def kadane_1d_with_indices(arr):
"""
Kadane's algorithm with left and right column indices
Returns: (left_index, right_index, max_sum)
"""
max_current = max_global = arr[0]
start = end = max_start = 0
current_start = 0
for i in range(1, len(arr)):
if arr[i] > max_current + arr[i]:
max_current = arr[i]
current_start = i
else:
max_current += arr[i]
if max_current > max_global:
max_global = max_current
max_start = current_start
end = i
return max_start, end, max_global
def extract_submatrix(matrix, top, bottom, left, right):
"""
Extract submatrix from coordinates
"""
submatrix = []
for i in range(top, bottom + 1):
row = []
for j in range(left, right + 1):
row.append(matrix[i][j])
submatrix.append(row)
return submatrix
def print_matrix(matrix):
"""Pretty print matrix"""
for row in matrix:
print([f"{val:3d}" for val in row])
# Test Maximum Submatrix Sum
print("\n" + "=" * 60)
print("PART 2: MAXIMUM SUBMATRIX SUM (2D) - O(N^3)")
print("=" * 60)
test_matrices = [
# Test case 1: Simple positive matrix
[
[1, 2, -1],
[-4, -5, -6],
[7, 8, 9]
],
# Test case 2: Mixed positive and negative
[
[2, 1, -1],
[-1, -4, -5],
[-1, -2, -3]
],
# Test case 3: All negative (pick least negative)
[
[-1, -2, -3],
[-4, -5, -6],
[-7, -8, -9]
],
# Test case 4: All positive
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
],
# Test case 5: 4x4 matrix
[
[1, -2, -3, 4],
[-5, 6, 7, -8],
[9, -10, 11, -12],
[-13, 14, -15, 16]
]
]
for idx, matrix in enumerate(test_matrices, 1):
print(f"\nTest Case {idx}:")
print("Matrix:")
print_matrix(matrix)
result = max_submatrix_sum(matrix)
print(f"\nResult:")
print(f" Maximum Sum: {result['max_sum']}")
print(f" Rows: {result['top_row']} to {result['bottom_row']}")
print(f" Cols: {result['left_col']} to {result['right_col']}")
submatrix = extract_submatrix(
matrix,
result['top_row'],
result['bottom_row'],
result['left_col'],
result['right_col']
)
print(f" Submatrix:")
print_matrix(submatrix)
Part 3: Complexity Analysis & Visualization
import time
import matplotlib.pyplot as plt
import numpy as np
def analyze_complexity():
"""
Analyze time complexity of algorithms
"""
print("\n" + "=" * 60)
print("COMPLEXITY ANALYSIS")
print("=" * 60)
# Kadane's 1D
print("\n1. Kadane's Algorithm (1D):")
print(" Time Complexity: O(n)")
print(" Space Complexity: O(1)")
print(" Why: Single pass through array, constant extra space")
print(" Operations per element: 2-3 comparisons/additions")
# Submatrix Sum
print("\n2. Maximum Submatrix Sum (2D):")
print(" Time Complexity: O(N³)")
print(" Space Complexity: O(N)")
print(" ")
print(" Breakdown:")
print(" - Top row selection: O(N)")
print(" - Bottom row selection: O(N)")
print(" - Column summing: O(N)")
print(" - Kadane on columns: O(N)")
print(" - Total: O(N²) × O(N) = O(N³)")
# Performance measurement
print("\n" + "-" * 60)
print("EMPIRICAL PERFORMANCE TEST")
print("-" * 60)
sizes = [10, 20, 50, 100, 200]
times_1d = []
times_2d = []
for size in sizes:
# 1D test
arr = np.random.randint(-100, 100, size)
start = time.perf_counter()
for _ in range(1000):
max_subarray_kadane(arr.tolist())
times_1d.append((time.perf_counter() - start) / 1000)
# 2D test (skip large sizes as O(N³) gets slow)
if size <= 100:
matrix = np.random.randint(-100, 100, (size, size))
start = time.perf_counter()
max_submatrix_sum(matrix.tolist())
times_2d.append(time.perf_counter() - start)
else:
times_2d.append(None)
print(f"\n{'Size':<10} {'1D Time (ms)':<15} {'2D Time (ms)':<15}")
print("-" * 40)
for i, size in enumerate(sizes):
t1d = times_1d[i] * 1000
t2d = times_2d[i] * 1000 if times_2d[i] is not None else "N/A (too slow)"
print(f"{size:<10} {t1d:<15.4f} {str(t2d):<15}")
# Run analysis
analyze_complexity()
# Visualization
def visualize_algorithms():
"""
Create visualization comparing algorithm performance
"""
print("\n" + "=" * 60)
print("ALGORITHM VISUALIZATION")
print("=" * 60)
# Show Kadane's algorithm step by step
arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(f"\nKadane's Algorithm Step-by-Step:")
print(f"Array: {arr}\n")
print(f"{'i':<3} {'arr[i]':<8} {'max_current':<15} {'max_global':<15}")
print("-" * 42)
max_current = max_global = arr[0]
print(f"{0:<3} {arr[0]:<8} {max_current:<15} {max_global:<15}")
for i in range(1, len(arr)):
max_current = max(arr[i], max_current + arr[i])
max_global = max(max_global, max_current)
print(f"{i:<3} {arr[i]:<8} {max_current:<15} {max_global:<15}")
visualize_algorithms()
Key Insights
Kadane's Algorithm (1D):
| Aspect | Details |
|---|
| Core Idea | Extend or restart subarray at each position |
| Choice | max(arr[i], prev_sum + arr[i]) |
| Time | O(n) - single pass |
| Space | O(1) - no extra data structures |
| Edge Cases | All negative numbers (returns max negative) |
Maximum Submatrix Sum (2D):
| Aspect | Details |
|---|
| Reduction | Convert 2D → multiple 1D problems |
| Row Pairs | Try all O(N²) combinations |
| For Each Pair | Apply Kadane on column sums O(N) |
| Time | O(N³) total |
| Space | O(N) for column sum array |
Optimization Possibilities:
- Optimized to O(N² × log N) using balanced BST
- O(N²) possible for specific matrices (researched but complex)
- Parallel Processing: Row pairs can be computed independently
This solution provides a complete implementation with multiple test cases, detailed explanations, and complexity analysis!