Skip to content

Edvins Antonovs

Richest customer wealth code challenge

My approach to solving LeetCode’s Richest customer wealth code challenge.


Problem

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

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

Solution

This code defines a function called maximumWealth that takes an array of accounts as input. It initializes a variable called rich with a value of 0. It then defines an inner function called sumUp, which takes an array as input and returns the sum of its elements using the reduce method.

The outer function then iterates through each element (an array) of the accounts array, and for each one, it calls the inner function sumUp to get the sum of the elements in that array. It then compares that sum to the current value of the rich variable. If the sum is greater than rich, it assigns the sum to rich.

Finally, the function returns the value of rich, representing the maximum sum of all the arrays in the accounts array.

1var maximumWealth = function (accounts) {
2 let rich = 0;
3
4 const sumUp = (arr) => arr.reduce((a, b) => a + b);
5
6 for (let i = 0; i < accounts.length; i++) {
7 if (sumUp(accounts[i]) > rich) {
8 rich = sumUp(accounts[i]);
9 }
10 }
11
12 return rich;
13};
© 2024 by Edvins Antonovs. All rights reserved.