본문 바로가기
LeetCode

1672. Richest Customer Wealth

by 싼쵸 2022. 5. 26.
반응형

문제

문제설명

2차원 배열 문제이다. 배열 안에 배열이 있는데, 배열안에 있는 수을 더해서 가장 큰 수를 리턴하는 문제이다.

 

나의 현재 풀이

/**
 * @param {number[][]} accounts
 * @return {number}
 */
var maximumWealth = function(accounts) {
    let arr = [];
    for(let i of accounts){
        arr.push(i.reduce((a,c)=> a+c))
    }
    return Math.max(...arr)
};

수를 더한 결과를 담는 arr 배열을 생성하고, for문을 통해 인자를 하나씩 꺼낸 다음 reduce 함수를 이용해서 다 더한 다음에 push를 통해 배열에 담았다. 그리고 리턴은 max 함수를 이용해 리턴했다.

 

나의 예전 풀이

/**
 * @param {number[][]} accounts
 * @return {number}
 */
var maximumWealth = function(accounts) {
    let size = accounts.length;
    let number = [size];
    let max = 0;
    let sum = 0;
    for(let i = 0; i < accounts.length; i++){
          number[i] = accounts[i].reduce((x,y) =>{
              return x + y;
          })   
        if(max < number[i]){
            max = number[i];
        }
    }
            
return max;
};

참 불필요한 변수를 많이 생성했다?? ㅋㅋㅋ저때에 비하면 확실히 발전을 하긴 했다 

 

다른 사람 풀이

var maximumWealth = function(accounts) {
        var res = 0;
        for(var i =0;i<accounts.length;i++){
            var temp = 0;
            for(var j = 0;j<accounts[i].length;j++){
                temp+=accounts[i][j];
            }
            res = Math.max(res,temp);
        }
        return res;
};

알고리즘의 매력은 같은 문제 푸는 사람마다 다른 시각으로 접근하기에 방법이 따른게 좀 큰 매력이다. 확실히 ㅋㅋ

반응형

'LeetCode' 카테고리의 다른 글

771. Jewels and Stones  (0) 2022.05.30
1512. Number of Good Pairs  (0) 2022.05.28
2011. Final Value of Variable After Performing Operations  (0) 2022.05.25
1480. Running Sum of 1d Array  (0) 2022.05.17
1920. Build Array from Permutation  (0) 2022.05.16

댓글