Sponsored
Sponsored
This approach involves iterating over each customer's accounts, calculating their total wealth by summing up the amounts, and keeping track of the maximum wealth found during these calculations. This method is simple and direct, leveraging basic iteration and comparison.
Time Complexity: O(m * n), where m is the number of customers and n is the number of banks.
Space Complexity: O(1), as we only use a few extra variables irrespective of input size.
1function maximumWealth(accounts) {
2 let maxWealth = 0;
3 for (const customer of accounts) {
4 const currentWealth = customer.reduce((a, b) => a + b, 0);
5 maxWealth = Math.max(maxWealth, currentWealth);
6 }
7 return maxWealth;
8}
9
10console.log(maximumWealth([[2,8,7],[7,1,3],[1,9,5]]));
The JavaScript code utilizes the reduce
function to sum each customer's accounts efficiently.
This approach considers a more functional programming style by mapping over the initial list to compute each customer's wealth, thereby generating an array of wealth values, which is in turn reduced (or simply searched) to obtain the maximum wealth.
Time Complexity: O(m * n)
Space Complexity: O(m)
1function maximumWealth(accounts) {
2
The solution uses map
to create an array of sums for each customer, and then Math.max
along with the spread operator to find the highest value.