java 1672.最富有的客户财富,这两个解决方案的区别只在一行(),但有没有人能解释一下这是如何产生区别的?

9jyewag0  于 2023-03-06  发布在  Java
关注(0)|答案(1)|浏览(84)

问题和测试用例位于leetcode链接中。https://leetcode.com/problems/richest-customer-wealth/description/解决方案1在第3次测试中失败,而解决方案2通过所有测试;唯一的区别在于突出显示的行。
溶液1:

class Solution {
    public int maximumWealth(int[][] accounts) {    
        int[] money = new int[accounts.length];
        for(int i=0;i<accounts.length;i++){
            for(int j=0;j<accounts[i].length;j++){
                money[i] = money[i] + accounts[i][j];
            }
        }
        return max(money);
    }
    static int max(int[] money){
        int great = money[0];
        for(int i=1;i<money.length;i++){
            if(money[i]>money[i-1]){    // This line has problem<<<-----------------------HERE
                great = money[i];
            }
        }
        return great;
    }
}

溶液2:

class Solution {
    public int maximumWealth(int[][] accounts) {    
        int[] money = new int[accounts.length];
        for(int i=0;i<accounts.length;i++){
            for(int j=0;j<accounts[i].length;j++){
                money[i] = money[i] + accounts[i][j];
            }
        }
        return max(money);
    }
    static int max(int[] money){
        int great = money[0];
        for(int i=1;i<money.length;i++){
            if(money[i]>great){          // this line is correct<<<-----------------------HERE
                great = money[i];
            }
        }
        return great;
    }
}
xxhby3vn

xxhby3vn1#

JavaScript解决方案

var maximumWealth = function(accounts) {
    let max_wealth = 0;
    accounts.forEach(item_i => {
        let item_i_wealth=0;
        item_i.forEach(item_j => {
            item_i_wealth=item_i_wealth+item_j;
        })
        max_wealth = max_wealth>item_i_wealth ? max_wealth : item_i_wealth;
    })
    return max_wealth
};

相关问题