Given an NxN matrix of positive and negative integers, write code to find the submatrix with the largest possible sum.
// "static void main" must be defined in a public class.
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
class Solution{
public int maxSubMatrix(int[][] nums) {
if(nums == null || nums.length == 0 || nums[0].length == 0){
return 0;
}
int r = nums.length;
int c = nums[0].length;
int maxSum = nums[0][0];
for(int i = 0; i < r; i++){
int[] sum = new int[c];
for(int j = i; j < r; j++){
for(int k = 0; k < c; k++){
sum [k] += nums[j][c];
}
int m = maxSubArray(sum);
maxSum = Math.max(maxSum, m);
}
}
}
public int maxSubArray(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
int maxSoFar = nums[0];
int maxEndingHere = nums[0];
for(int i = 1; i < nums.length; i++){
maxEndingHere = Math.max(maxEndingHere + nums[i], nums[i]);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
}