机试【二】求连续的最长子串和

本文介绍了一种使用动态规划(DP)方法解决的最大子串和问题,并提供了一个具体的Java实现案例。通过递推公式更新每个位置的最大子串和,最终找到整个数组中最大的连续子数组之和。

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

package com.promise.demo;

public class MaxSubSum {



//    DP法求解 最大子串和
    public static int maxSubSum(int[] array){
        if(array == null)
        {
            return 0;
        }

        int n = array.length;
        int[] end = new int[n];
        int[] res = new int[n];

        end[0] = array[0];
        res[0] = array[0];

        for(int i=1;i<n;i++){
            end[i] = Integer.max(array[i],end[i-1]+array[i]);
            res[i] =Integer.max(end[i],res[i-1]);

        }

        return res[n-1];
    }


    public static void main(String[] args){
        int[] array = {1,-2,4,8,-4,7,-1,-5};

        int max = maxSubSum(array);
        System.out.println(max);




    }



}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值