프로그래밍/Online Judge

LeetCode) 1672.Richest Customer Wealth 풀이 (with.JavaScript)

삐제제 2021. 5. 14. 01:24

난이도 : Easy

 

문제 : 

You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ 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

 

Example 2:

Input: accounts = [[1,5],[7,3],[3,5]]

Output: 10

 

Example 3:

Input: accounts = [[2,8,7],[7,1,3],[1,9,5]] Output: 17

 

 

풀이 :

/**
 * @param {number[][]} accounts
 * @return {number}
 */
var maximumWealth = function(accounts) {
    var sum = 0;
    var max = 0;
    for(i = 0; i < accounts.length; i++){
        for (j = 0; j < accounts[i].length; j++){
            sum += accounts[i][j];
        }
        if(sum > max){
            max = sum;
        }
        sum = 0; // sum 값 초기화
    }
    return max;
};

 

2차원배열에서 각 행들의 값을 더한 후, 그 최댓값을 return 하는 문제입니다.

 

중첩 포문으로 각 행 내부의 합을 sum 변수에 할당한 후

sum이 max(최댓값을 저장할 변수) 보다 크다면, sum을 max 에 할당하여 2차원 배열 내부의 각 행 내부의 합들의 최댓값을 구할 수 있습니다.