LeetCode(Array) 1672. Richest Customer Wealth

今天药忘吃喽~ 2023-09-23 22:39 105阅读 0赞

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:

  1. class Solution {
  2. public int maximumWealth(int[][] accounts) {
  3. int max =0;//1.定义max初始值为0
  4. for (int i = 0; i < accounts.length; i++) {
  5. //2.遍历数组行的长度
  6. int sum=0;//定义变量sum为0
  7. for(int j =0;j<accounts[i].length;j++){
  8. //3.遍历数组的列,将数组内的值相加
  9. sum+=accounts[i][j];
  10. }
  11. max=Math.max(max,sum); //4.比较sum和max的最大值,取最大值作为max
  12. //if (sum > max) max = sum 如果不是用Math.max()方法,可以直接用if判断
  13. }
  14. return max;//5.返回max
  15. }
  16. }

解题思路和以上基本相同,不同的在于使用for each遍历

  1. class Solution {
  2. public int maximumWealth(int[][] accounts) {
  3. int max = 0;
  4. for(int[] account : accounts){
  5. int sum = 0;
  6. for(int s : account){
  7. sum = sum + s;
  8. }
  9. max = Math.max(max, sum);
  10. }
  11. return max;
  12. }
  13. }

代码2:

  1. class Solution {
  2. public int maximumWealth(int[][] accounts) {
  3. int maxWealth = 0;
  4. for (int[] customer : accounts){
  5. //解题思路基本相同,不同的是使用Arrays.stream(customer).sum()方法,将数组中的所有值遍历再相加
  6. maxWealth = Math.max(maxWealth, Arrays.stream(customer).sum());
  7. }
  8. return maxWealth;
  9. }
  10. }

`

发表评论

表情:
评论列表 (有 0 条评论,105人围观)

还没有评论,来说两句吧...

相关阅读