LeetCode(Array) 1672. Richest Customer Wealth
1.问题
You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the ith customer has in the jth bank. Return the wealth that the richest customer has.
A customer’s wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.
Example 1:
Input: accounts = [[1,2,3],[3,2,1]]
Output: 6
Explanation:
1st customer has wealth = 1 + 2 + 3 = 6
2nd customer has wealth = 3 + 2 + 1 = 6
Both customers are considered the richest with a wealth of 6 each, so return 6.
Example 2:
Input: accounts = [[1,5],[7,3],[3,5]]
Output: 10
Explanation:
1st customer has wealth = 6
2nd customer has wealth = 10
3rd customer has wealth = 8
The 2nd customer is the richest with a wealth of 10.
Example 3:
Input: accounts = [[2,8,7],[7,1,3],[1,9,5]]
Output: 17
Constraints:
- m == accounts.length
- n == accounts[i].length
- 1 <= m, n <= 50
- 1 <= accounts[i][j] <= 100
2. 解题思路
方法1:
1.定义max初始值为0
2.遍历数组行的长度
3.遍历数组的列,将数组内的值相加
4.比较sum和max的最大值,取最大值作为max
5.返回max
方法2:
解题思路和方法1基本相同,不同的是使用Arrays.stream(customer).sum()方法,将数组中的所有值遍历再相加
3. 代码
代码1:
class Solution {
public int maximumWealth(int[][] accounts) {
int max =0;//1.定义max初始值为0
for (int i = 0; i < accounts.length; i++) {
//2.遍历数组行的长度
int sum=0;//定义变量sum为0
for(int j =0;j<accounts[i].length;j++){
//3.遍历数组的列,将数组内的值相加
sum+=accounts[i][j];
}
max=Math.max(max,sum); //4.比较sum和max的最大值,取最大值作为max
//if (sum > max) max = sum 如果不是用Math.max()方法,可以直接用if判断
}
return max;//5.返回max
}
}
解题思路和以上基本相同,不同的在于使用for each遍历
class Solution {
public int maximumWealth(int[][] accounts) {
int max = 0;
for(int[] account : accounts){
int sum = 0;
for(int s : account){
sum = sum + s;
}
max = Math.max(max, sum);
}
return max;
}
}
代码2:
class Solution {
public int maximumWealth(int[][] accounts) {
int maxWealth = 0;
for (int[] customer : accounts){
//解题思路基本相同,不同的是使用Arrays.stream(customer).sum()方法,将数组中的所有值遍历再相加
maxWealth = Math.max(maxWealth, Arrays.stream(customer).sum());
}
return maxWealth;
}
}
`
还没有评论,来说两句吧...