在锯齿状数组 C# 中查找每个数组的总和

问题描述

我希望接收一个 int[][] 类型的锯齿状数组,然后遍历数组以找到总和最高的特定数组,然后返回该总和。我在网上做了一些挖掘,但没有找到太多关于如何单独总结每个数组的信息。

例如,如果这是接收到的输入:

int[][] accounts = new int[3][];
            accounts[0] = new int[] { 1,2,3};
            accounts[1] = new int[] { 2,3,4 };
            accounts[2] = new int[] { 3,4,5 };

我最接近的是获取所有元素的总和

for (var i = 0; i < accounts.Length; i++)
{
    for (var j = 0; j < accounts[i].Length; j++)
        {
            sum += accounts[i][j];
        }
}

我遗漏了哪一步来分隔数组并单独求和?

解决方法

您的问题是您没有保持最大值。

给定

const items = [
  {
    category: "Social",areasAffected: ["Area_01","Area_02"],},{
    category: "Environmental","Area_02","Area_03","Area_04"],];

const filterChallenges = (items,filters) => {
  const filterKeys = Object.keys(filters);

  return items.filter((item) => {
    // ALL of the filters must be matched (.every())
    return filterKeys.every((filterKey) => {
      if (!Array.isArray(item[filterKey])) {
        const candidateValue = item[filterKey].toString().toLowerCase();
        // ALL of the filter values must be included in the item value
        // (.every())
        return filters[filterKey].every((filterEle) =>
          candidateValue.includes(filterEle.value.toString().toLowerCase())
        );
      }

      // Value is an array,ONE element (.some()) must match ALL of the
      // filter values (.every())
      return item[filterKey].some((candidate) => {
        const candidateValue = candidate.toString().toLowerCase();
        return filters[filterKey].every((filterEle) =>
          candidateValue.includes(filterEle.value.toString().toLowerCase())
        );
      });
    });
  });
};

const ret = filterChallenges(items,{
  category: [{ value: "Social",label: "Social" }],areasAffected: [{ value: "Area_01",label: "Area_01" }],});

console.log(ret);

示例

.toString()

但是,让我们看看如何使这更简洁。

您可以使用 var accounts = new int[][] { new[] {1,2,3},new[] {2,3,4},new[] {3,4,5} };

var max = 0;
for (var i = 0; i < accounts.Length; i++)
{
   var sum = 0;
   for (var j = 0; j < accounts[i].Length; j++)
      sum += accounts[i][j];
   if (sum > max) 
      max = sum;
}

您可以使用 Linq foreach

foreach (var array in accounts)
{
   var sum = 0;
   foreach (var item in array)
      sum += item;
   if (sum > max) 
      max = sum;
}

或者你可以使用 Linq Sumforeach (var array in accounts) { var sum = array.Sum(); if (sum > max) max = sum; }

Max

其他资源

Enumerable.Max Method

返回值序列中的最大值。

Enumerable.Sum Method

计算一系列数值的总和。

,

对您当前的尝试实施一个简单的修复方法是跟踪目前看到的 maxAccountSum

using System;

class MainClass
{
    public static void Main (string[] args)
    {
        int[][] accounts = new int[3][];
        accounts[0] = new int[] { 1,3 };
        accounts[1] = new int[] { 2,4 };
        accounts[2] = new int[] { 3,5 };     
        
        var maxAccountSum = Int32.MinValue; // To account for if the accounts have negative balances? Like they were all overdrafted or something.
        for (var i = 0; i < accounts.Length; i++)
        {
            var accountSum = 0;
            for (var j = 0; j < accounts[i].Length; j++)
            {
                accountSum += accounts[i][j];
            }
            maxAccountSum = Math.Max (maxAccountSum,accountSum);
        }

        Console.WriteLine ("The highest sum in an account is {0}.",maxAccountSum);
    }
}

时空分析:

  • O(mn) 时间,其中 m 是帐户数,n 是单个帐户中的最大值数。
  • O(1) 空间,因为我们只跟踪几个额外的变量。

输出:

The highest sum in an account is 12.