public class Solution {
// private int maxSubArrayLessK(int[] arr, int k) { Wrong Answer for [27, 16, 24, 28, 7, -7, -3, -20, 23, 5, 13, 15, 15, 26, -19] -100
// int end = 0;
// int sum = 0, res = Integer.MIN_VALUE;
// int len = arr.length;
// for (int start = 0; start < len; start++) {
// while (end < len && sum + arr[end] <= k) {
// sum += arr[end++];
// res = Math.max(res, sum);
// }
// if (end == len && sum <= k) {
// res = Math.max(res, sum);
// }
// sum -= arr[start];
// }
// return res;
// }
private int maxSubArrayLessK(int[] a , int k){
int max = Integer.MIN_VALUE;
int sumj = 0;
TreeSet<Integer> s = new TreeSet();
s.add(0);
for(int i=0;i<a.length;i++){
int t = sumj + a[i];
sumj = t;
Integer gap = s.ceiling(sumj - k);
if(gap != null) max = Math.max(max, sumj - gap);
s.add(t);
}
return max;
}
public int maxSumSubmatrix(int[][] matrix, int k) {
int row = matrix.length, col = matrix[0].length;
int res = Integer.MIN_VALUE;
for (int left = 0; left < col; left++) {
int[] temp = new int[row];
for (int right = left; right < col; right++) {
for(int i = 0; i < row; i++) {
temp[i] += matrix[i][right];
}
res = Math.max(res, maxSubArrayLessK(temp, k));
}
}
return res;
}
}
/*
[[5,-4,-3,4],[-3,-4,4,5],[5,1,5,-4]]
8
Expected Answer 8
*/
public class Solution {
public static int maxSumSubArrayNoGreaterThanK(int[] s, int k) {
int len = s.length;
int ans = Integer.MIN_VALUE;
int nums[] = new int[len];
nums[0] = s[0];
for(int i=1;i<len;i++){
nums[i] = nums[i-1] + s[i];
}
for(int i=0;i<len;i++){
for(int j=i;j<len;j++){
int sum;
if(i==0) sum = nums[j];
else sum = nums[j] - nums[i-1];
if(sum > ans && sum <= k)
ans = sum;
}
}
return ans;
}
public int maxSumSubmatrix(int[][] matrix, int k) {
int cols = matrix[0].length;
int rows = matrix.length;
int maxSum = Integer.MIN_VALUE;
for (int leftCol = 0; leftCol < cols; leftCol++) {
int[] tmp = new int[rows];
for (int rightCol = leftCol; rightCol < cols; rightCol++) {
for (int l = 0; l < rows; l++) {
tmp[l] += matrix[l][rightCol];
}
int currentResult = maxSumSubArrayNoGreaterThanK(tmp,k);
if (currentResult > maxSum) {
maxSum = currentResult;
}
}
}
return maxSum;
}
}