求一個矩陣中最大的二維矩陣(元素和最大)

求一個矩陣中最大的二維矩陣(元素和最大). :
1 2 0 3 4
2 3 4 5 1
1 1 5 3 0
中最大的是
:
4 5
5 3
要求:(1)寫出算法;(2)分析時間複雜度;(3)C寫出關鍵代碼
java

 

public class FindMax2DimensionMatrix {
	public static void main(String args[]) {
		int arr[] = { -1, 2, -3, -1, 20, -100, -34 };
		System.out.println(findOneDimensionMaxSum(arr));
		//1 2 0 3 4
//		2 3 4 5 1
//		1 1 5 3 0
		int matrix[][] = {{1,2,0,3,4}, {2,3,4,5,1}, {1,1,5,3,0}};
//		System.out.println(execute(matrix));
		System.out.println(findOneDimensionMaxSumWithStep(arr, 4));
	}

	public static int findOneDimensionMaxSumWithStep(int[] oneDMatrix, int step){
		int max = 0;
		int tmp = 0;
		for (int i = 0; i < oneDMatrix.length - (step - 1); i++) {
			for(int j = 0; j < step; j++){
			    tmp += 	oneDMatrix[i + j];
			}
			
			if (max < tmp) {
				max = tmp;
			} 
			
			tmp = 0;
		}
		
		return max;
	}
	
	public static int findOneDimensionMaxSum(int[] oneDMatrix) {
		int max = 0;
		int tmp = 0;
		for (int i = 0; i < oneDMatrix.length; i++) {
			tmp = tmp + oneDMatrix[i];
			if (max < tmp) {
				max = tmp;
			} else {
				if (tmp < 0) {
					tmp = 0;
				}
			}
		}

		return max;
	}

	public static int execute(int[][] matrix) {
		int finalMax = 0;
		int tmp = 0;
		int height = matrix.length;
		int width = matrix[0].length;
		for (int j = 0; j < width - 1; j++) {
			int max = 0;
			for (int i = 0; i < height; i++) {
                tmp = max + matrix[i][j] + matrix[i][j + 1];
                if(tmp > max){
                	max = tmp;
                }
                
                if(tmp < 0){
                	tmp = 0;
                }
			}
			
			if(finalMax < max){
				finalMax = max;
			}
		}
		
		return finalMax;
	}
}
相關文章
相關標籤/搜索