从数组中获取最大子和

编程入门 行业动态 更新时间:2024-10-11 11:20:28
本文介绍了从数组中获取最大子和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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]总和最大

更多推荐

从数组中获取最大子和

本文发布于:2023-11-29 04:28:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645281.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:大子   组中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!