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
출처 : https://leetcode.com/problems/richest-customer-wealth/description/
풀이
function maximumWealth(accounts: number[][]): number {
return Math.max(...accounts.map(x=>x.reduce((a,b)=>a+b,0)));
};
- accounts.map(x => x.reduce((a, b) => a + b, 0)):
- accounts.map(...)는 accounts 배열의 각 요소에 대해 함수를 적용하여 새로운 배열을 만든다.
- x.reduce((a, b) => a + b, 0)는 배열 x (배열의 요소)를 하나의 숫자로 합산. reduce 함수는 배열의 각 요소를 누적하여 하나의 값으로 만듦. 초기값 0에서 시작하여 a + b로 누적.
- accounts.map(x => x.reduce((a, b) => a + b, 0))는 각 배열의 모든 값 합계를 요소로 가지는 새로운 배열을 만듦.
- Math.max(...[합계들]):
- Math.max 함수는 주어진 숫자들 중 최대값을 반환
- ... (전개 연산자)는 배열을 개별 요소로 펼쳐줌. 따라서 [합계들] 배열의 각 요소를 개별적인 인수로 Math.max에 전달하여 최대값을 찾는다.
x.reduce((a, b) => a + b, 0)에서 a와 b는 각각 누적값과 현재 배열 요소를 나타냄.
- reduce 함수는 배열의 각 요소를 순회하면서 누적 연산을 수행.
- (a, b) => a + b는 reduce 함수에 전달된 콜백 함수로, 두 개의 매개변수 a와 b를 받음.
- a는 누적값 (accumulator).
- b는 현재 처리 중인 배열 요소.
- 0은 reduce 함수의 초기값.
예를 들어, 배열 x가 [1, 2, 3, 4]인 경우:
- 첫 번째 순회:
- 초기값 a는 0
- 현재 요소 b는 1
- 계산: 0 + 1 = 1
- 두 번째 순회:
- 현재 누적값 a는 1
- 현재 요소 b는 2
- 계산: 1 + 2 = 3
- 세 번째 순회:
- 현재 누적값 a는 3
- 현재 요소 b는 3
- 계산: 3 + 3 = 6
- 네 번째 순회:
- 현재 누적값 a는 6
- 현재 요소 b는 4
- 계산: 6 + 4 = 10
'LeetCode' 카테고리의 다른 글
| 2287. Rearrange Characters to Make Target String / TypeScript (0) | 2024.06.04 |
|---|---|
| 1407. Top Travellers (0) | 2024.06.03 |
| 589. N-ary Tree Preorder Traversal / TypeScript (1) | 2024.06.01 |
| 2629. Function Composition / TypeScript (0) | 2024.05.31 |
| 2566. Maximum Difference by Remapping a Digit / TypeScript (0) | 2024.05.30 |