LeetCode 1672:JavaScript实现嵌套数组求和找最富客户财富
LeetCode 1672 最富客户的财富问题解决
问题分析
你的代码核心问题出在递归逻辑误用和变量处理错误:
- 题目给定的是二维数组
accounts,外层数组每个元素是单个客户的所有银行存款(一维数组),完全不需要递归遍历整个结构。你当前的递归调用会把所有嵌套数组的数值都累加到同一个total里,而且递归过程中内层函数的totalArr是局部变量,外层的totalArr只会在第一次处理子数组时push值,后续操作根本不会影响它。 - 处理每个客户的存款时,
total没有重置,导致后续客户的存款会和之前的累加在一起,而不是单独计算每个客户的财富。
修复后的代码方案
方案1:基础循环实现
遍历每个客户的账户数组,单独计算每个客户的财富,再实时更新最大值:
/** * @param {number[][]} accounts * @return {number} */ const maximumWealth = (accounts) => { let maxWealth = 0; // 遍历每个客户的账户列表 for (let i = 0; i < accounts.length; i++) { let currentCustomerWealth = 0; // 计算当前客户的总存款 for (let j = 0; j < accounts[i].length; j++) { currentCustomerWealth += accounts[i][j]; } // 更新最大财富值 if (currentCustomerWealth > maxWealth) { maxWealth = currentCustomerWealth; } } return maxWealth; };
方案2:数组API简化实现
利用map遍历每个客户的账户,用reduce计算单个客户的财富总和,最后用Math.max找出最大值:
/** * @param {number[][]} accounts * @return {number} */ const maximumWealth = (accounts) => { // 先生成所有客户的财富数组,再取最大值 const allWealths = accounts.map(customer => customer.reduce((sum, money) => sum + money, 0)); return Math.max(...allWealths); };
测试用例验证
- 示例1输入
[[1,2],[3,4],[5,6]]:
方案2中allWealths会得到[3,7,11],最终返回最大值11,符合题目要求。 - 示例2输入
[[1,2,3],[3,2,1]]:allWealths得到[6,6],返回6,结果正确。
内容的提问来源于stack exchange,提问作者elborracho420
相关产品推荐
相关产品推荐

