Repository navigation
Expand file tree
/
Copy path38-MaxRowAndColumnSum.java
More file actions
56 lines (51 loc) · 1.83 KB
/
Copy path38-MaxRowAndColumnSum.java
File metadata and controls
56 lines (51 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.Scanner;
class MaxRowAndColumnSum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[][] matrix = readMatrix(scanner);
if (matrix.length == 0) {
System.out.println("Matrix is empty");
} else {
int maxRow = 0;
int maxRowSum = Integer.MIN_VALUE;
for (int i = 0; i < matrix.length; i++) {
int rowSum = 0;
for (int value : matrix[i]) {
rowSum += value;
}
if (rowSum > maxRowSum) {
maxRowSum = rowSum;
maxRow = i;
}
}
int maxColumn = 0;
int maxColumnSum = Integer.MIN_VALUE;
int columns = matrix[0].length;
for (int j = 0; j < columns; j++) {
int columnSum = 0;
for (int i = 0; i < matrix.length; i++) {
columnSum += matrix[i][j];
}
if (columnSum > maxColumnSum) {
maxColumnSum = columnSum;
maxColumn = j;
}
}
System.out.println("Row with maximum sum: " + maxRow + " (sum " + maxRowSum + ")");
System.out.println("Column with maximum sum: " + maxColumn + " (sum " + maxColumnSum + ")");
}
scanner.close();
}
private static int[][] readMatrix(Scanner scanner) {
System.out.print("Enter rows and columns: ");
int rows = scanner.nextInt();
int columns = scanner.nextInt();
int[][] matrix = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix[i][j] = scanner.nextInt();
}
}
return matrix;
}
}