44.开发商购买土地
题目链接:https://kamacoder.com/problempage.php?pid=1044
题目讲解:44. 开发商购买土地 | 代码随想录
题目思路:前缀和 (统计每行每列的总和,再进行比较,比较出最小值)
import java.util.Scanner;
public class Exercise{
public static void main(String[] args){
Scanner myS = new Scanner(System.in);
int n = myS.nextInt();
int m = myS.nextInt();
int[][] ans = new int[n][m];
int sum = 0; //所有数据总和
for(int i = 0;i<n;i++){
for(int j = 0;j<m;j++){
ans[i][j] = myS.nextInt();
sum = sum + ans[i][j];
}
}
//计算每行的总和
int[] row = new int[n];
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
row[i] = row[i] + ans[i][j];
}
}
//计算每列的总和
int[] col = new int[m];
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j++){
col[i] = col[i] + ans[j][i];
}
}
//对每行前缀和进行比较
int result = Integer.MAX_VALUE;
int res = 0;
for(int i = 0;i < n;i++){
res = res + row[i];
result = Math.min(result , Math.abs((sum - res) - res));
}
//对每列前缀和进行比较
res = 0;
for(int j = 0;j < m;j++){
res = res + col[j];
result = Math.min(result , Math.abs((sum - res) - res));
}
System.out.println(result);
}
}
数组小结
章末总结:代码随想录