Advertisement
Guest User

Untitled

a guest
Aug 17th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. public class Solution {
  2.  
  3. public static int maxSumSubArrayNoGreaterThanK(int[] s, int k) {
  4. int len = s.length;
  5. int ans = Integer.MIN_VALUE;
  6. int nums[] = new int[len];
  7. nums[0] = s[0];
  8. for(int i=1;i<len;i++){
  9. nums[i] = nums[i-1] + s[i];
  10. }
  11.  
  12. for(int i=0;i<len;i++){
  13. for(int j=i;j<len;j++){
  14. int sum;
  15. if(i==0) sum = nums[j];
  16. else sum = nums[j] - nums[i-1];
  17. if(sum > ans && sum <= k)
  18. ans = sum;
  19. }
  20. }
  21. return ans;
  22. }
  23.  
  24.  
  25. public int maxSumSubmatrix(int[][] matrix, int k) {
  26. int cols = matrix[0].length;
  27. int rows = matrix.length;
  28. int maxSum = Integer.MIN_VALUE;
  29.  
  30. for (int leftCol = 0; leftCol < cols; leftCol++) {
  31. int[] tmp = new int[rows];
  32. for (int rightCol = leftCol; rightCol < cols; rightCol++) {
  33. for (int l = 0; l < rows; l++) {
  34. tmp[l] += matrix[l][rightCol];
  35. }
  36. int currentResult = maxSumSubArrayNoGreaterThanK(tmp,k);
  37. if (currentResult > maxSum) {
  38. maxSum = currentResult;
  39. }
  40. }
  41. }
  42. return maxSum;
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement