js连续子数组最大和

该代码段使用JavaScript遍历数组consta,计算其中连续子数组的最大和。变量total用于存储当前子数组的累计和,index存储最大子数组的起始索引。通过遍历数组并比较total+c与c的值,更新total以找到最大和。最后输出最大和以及最大子数组的起始索引。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

const a = [0.01, -0.02, 0.03, 0.1, -0.04, 0.07, 0.02, -0.05]
    let total = 0
    let index = 0
		//连续子数组最大和 
		// 0.03 + 0.1 + (-0.04) + 0.07 + 0.02 = 0.18
    a.forEach((c)=>{
        total =  Math.max(total+c,c)
        index = Math.max(total,index)
        // total+=c
        // if(total<c){
        //     total = c
            
        // }
        // if(index<total){
        //     index=total
        // }
        // console.log(total,'total-----')
    })
    console.log(index,total,'index----')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值