Javascript算法最大子数组

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

我从leet代码中得到了这个问题,而我从YouTube教程中得到了这个答案,但是我不明白max的部分.因为max是arr[0]并且值是-2,即使它进入循环内部,它也只是-2,但是max返回值6.

I get that question from leet code and I got this answer from YouTube tutorial, but I don't understand the part of max. Because max is arr[0] and the value is -2, and even it goes inside of the loop, it is just -2 but max returns value 6.

怎么可能?

const givenArray = [-2, 1, -3, 4, -1, 2, 1, -5, 4]; const getMax = arr => { let sum = arr[0]; //-2 let max = arr[0]; //-2 for (let i = 1; i < arr.length; i++) { sum = Math.max(sum + arr[i], arr[i]); max = Math.max(max, sum); } console.log(sum); console.log(max); }; getMax(givenArray);

推荐答案

max = -2 sum = -2

max=-2 sum=-2

loop arr [1] = 1:sum = max(-2 + 1,1)= 1,max = max(sum = 1,max = -2)= 1

loop arr[1]=1: sum = max( -2 + 1, 1) = 1, max = max( sum=1 , max=-2 ) = 1

max = 1 sum = 1

max=1 sum=1

loop arr [2] =-3:sum = max(1 + -3,-3)= -2,max = max(sum = -2,max = 1)= 1

loop arr[2]=-3: sum = max( 1 + -3, -3) = -2, max = max( sum=-2, max=1 ) = 1

max = 1 sum = -2

max=1 sum=-2

loop arr [3] = 4:sum = max(-3 + 4,4)= 4,max = max(sum = 4,max = 1)= 4

loop arr[3]=4: sum = max( -3 + 4, 4) = 4, max = max( sum=4, max=1 ) = 4

max = 4 sum = 4

max=4 sum=4

loop arr [4] =-1:sum = max(4 + -1,-1)= 3,max =(3,4)= 4

loop arr[4]=-1: sum = max( 4 + -1, -1) = 3, max = (3,4) = 4

max = 4 sum = 3

max=4 sum=3

loop arr [5] = 2:sum = max(3 + 2,2)= 5,max = max(5,4)= 5

loop arr[5]=2: sum = max( 3 + 2, 2) = 5, max = max(5,4) = 5

所以迭代看起来像这样:

So the iteration looks like this:

arr [-2, 1, -3, 4, -1, 2, 1, -5, 4] sum x, 1, x, 4, 3, 5, 6, 1, 5 max -2, 1, 1, 4, 4, 5, 6, 6, 6

这就像查找累加和,丢弃负序列或在和为负时开始新序列一样,因为任何负序列都会对序列的总和产生负面影响.

It's like finding progressive sums, discarding negative sequences or starting off a new sequence when sum is negative, because any negative sequence would contribute negatively to the total sum of a sequence.

然后,您使用max = Math.max(max,sum),(将max设置为更大的值,当前最大值或当前总和)来找到渐进总和中达到的最大值(为6). > 这也说明了所有负数的边缘情况,其中最大和为最大负数.

And, you use max = Math.max(max, sum), (set max to what's bigger, current max value or current sum) to find the largest value reached in the progressive sums (which is 6). This also accounts for edge case of all negatives, where the maximal sum will be the largest negative number.

const givenArray = [-2, 1, -3, 4, -1, 2, 1, -5, 4]; const getMax = arr => { let sum = arr[0]; //-2 let max = arr[0]; //-2 for (let i = 1; i < arr.length; i++) { sum = Math.max(sum + arr[i], arr[i]); max = Math.max(max, sum); console.log(`max=${max}`, `sum=${sum}`); } }; getMax(givenArray);

更多推荐

Javascript算法最大子数组

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

发布评论

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

>www.elefans.com

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