从数组中获取最大子和 [英] Get max subsum from an array

查看:32
本文介绍了从数组中获取最大子和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在一次测试中遇到了这个问题,完全不明白这个问题的要求是什么,尤其是基于示例:

I had this question on a test recently and don't understand at all what the question is asking for, especially based on the examples:

ma​​x_subsum

编写一个方法,max_subsum(numbers),它接受一个数组并返回具有的连续范围的开始和结束索引最大的总和.

Write a method, max_subsum(numbers), which takes an array and returns the start and end indices of the consecutive range which has the largest sum.

max_subsum([100, -101, 200, -3, 1000]) == [2, 4]

max_subsum([100, -101, 200, -3, 1000]) == [2, 4]

max_subsum([1, 2, 3]) == [0, 2]

max_subsum([1, 2, 3]) == [0, 2]

提示:遍历所有子数组;计算每个的总和子数组并与迄今为止看到的最大子和进行比较.一个子数组是由它的开始索引和结束索引定义,所以遍历所有指数对.您可能应该使用两个循环,一个嵌套在里面另一个.

Hints: iterate through all the subarrays; compute the sum of each subarray and compare to the max subsum seen so far. A subarray is defined by its start index and end indices, so iterate through all pairs of indices. You should probably use two loops, one nested inside the other.

我在示例中没有看到任何子数组.示例的输出仅显示数组中最小值和最大值的索引.如果这就是问题所要求的,那么子数组的总和正在发生.我一定错过了一些简单的东西,我只是不知道那是什么.别人看到了吗?

I don't see any subarrays in the examples. The output from the examples simply shows the indices of smallest and largest values in the array. If that's what the question is asking for, then what summation of subarrays is happening. I must be missing something simple, I just don't know what that is. Does someone else see it?

推荐答案

这些是第一个数组的子数组及其和:

These are the first array's subarrays along with their sums:

[100].inject(:+)                       #=>   100
[100, -101].inject(:+)                 #=>    -1
[100, -101, 200].inject(:+)            #=>   199
[100, -101, 200, -3].inject(:+)        #=>   196
[100, -101, 200, -3, 1000].inject(:+)  #=>  1196
     [-101].inject(:+)                 #=>  -101
     [-101, 200].inject(:+)            #=>    99
     [-101, 200, -3].inject(:+)        #=>    96
     [-101, 200, -3, 1000].inject(:+)  #=>  1096
           [200, -3, 1000].inject(:+)  #=>  1197
                [-3, 1000].inject(:+)  #=>   997
                    [1000].inject(:+)  #=>  1000

[200, -3, 1000]总和最大

这篇关于从数组中获取最大子和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆