首页 > 解决方案 > Javascript - 获取数组中最大数组总和的最佳方法

问题描述

我有以下数组:

   arr = [
     [ 1, 1, 1, 1, 1, 1, 1 ],
     [ 1, 1, 0, 0, 1, 1, 0 ],
     [ 1, 0, 0, 0, 1, 0, 0 ],
     [ 0, 0, 0, 0, 0, 0, 0 ],
     [ 0, 1, 0, 1, 0, 0, 2 ],
     [ 1, 0, 0, 1, 0, 2, 4 ],
     [ 0, 0, 0, 0, 2, 4, 4 ],
     [ 0, 0, 0, 0, 4, 4, 0 ],
     [ 1, 1, 1, 0, 0, 0, 0 ],
     [ 1, 1, 0, 2, 0, 0, 2 ],
     [ 1, 0, 0, 4, 0, 2, 0 ],
     [ 0, 0, 0, 4, 2, 0, 0 ],
     [ 0, 0, 2, 0, 0, 0, 1 ],
     [ 0, 2, 4, 0, 0, 1, 2 ],
     [ 2, 4, 4, 2, 1, 2, 4 ],
     [ 4, 4, 0, 0, 2, 4, 0 ]
  ]

目前,我正在arr像这样获得 ie 19中的最大数组总和

   function getMaxSum(arr) {
      return arr.map(e => e.reduce((a, b) => a + b, 0)).sort((a,b) => a - b)[arr.length - 1];
   }

标签: javascriptarrays

解决方案


不是一个巨大的改进,但将值传播到Math.max

const data = [
     [ 1, 1, 1, 1, 1, 1, 1 ],
     [ 1, 1, 0, 0, 1, 1, 0 ],
     [ 1, 0, 0, 0, 1, 0, 0 ],
     [ 0, 0, 0, 0, 0, 0, 0 ],
     [ 0, 1, 0, 1, 0, 0, 2 ],
     [ 1, 0, 0, 1, 0, 2, 4 ],
     [ 0, 0, 0, 0, 2, 4, 4 ],
     [ 0, 0, 0, 0, 4, 4, 0 ],
     [ 1, 1, 1, 0, 0, 0, 0 ],
     [ 1, 1, 0, 2, 0, 0, 2 ],
     [ 1, 0, 0, 4, 0, 2, 0 ],
     [ 0, 0, 0, 4, 2, 0, 0 ],
     [ 0, 0, 2, 0, 0, 0, 1 ],
     [ 0, 2, 4, 0, 0, 1, 2 ],
     [ 2, 4, 4, 2, 1, 2, 4 ],
     [ 4, 4, 0, 0, 2, 4, 0 ]
  ]

function getMaxSum(arr) {
  return Math.max(...arr.map(e => e.reduce((a, b) => a + b, 0)))
}

console.log(getMaxSum(data))


正如@Rajesh 指出的那样, Math.max 比排序更快:

const numbers = Array(10000).fill().map((x,i)=>i);

const max = numbersIn => Math.max(...numbersIn);
const getMaxViaSort = numbersIn => numbersIn
  .sort((a, b) => a > b ? -1 : 1)[0]

console.time('max');
max(numbers);
console.timeEnd('max');

console.time('max via sort');
getMaxViaSort(numbers);
console.timeEnd('max via sort');


推荐阅读