最大子串和

该博客介绍了一个寻找数组中最大和连续子数组的Java程序。通过遍历数组,比较相邻元素之和与当前元素的关系,更新最大子数组的起始位置、结束位置和最大和。最终输出最大子数组的和及其下标。

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

介个题与前面leetcode分析的那个题一模一样捏

比较(a[i]+a[i+1])的值和a[i+1]的值,如果大于的话则继续,如果小于的话则从a[i+1]开始。用for循环寻找最大和的连续子数组。

import java.util.Scanner;
public class MaxSum {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner sc=new Scanner(System.in);
       // System.out.println("输入数组长度");
       // int n=sc.nextInt();System.out.println("输入数组数据(用空格分开)");
        int i;
        int a[]={-2,11,-4,13,-5,-2};
       // for(i=0;i<n;i++)
         //   a[i]=sc.nextInt();

        int begin=0;//子数组开始下标
        int end=0;//子数组结束下标
        int maxValue=a[0];
        int tempValue=maxValue;


        //for循环寻找最大和的连续子数组
        for(i=1;i<5;i++)
        {
            tempValue+=a[i];
            if((tempValue>a[i])&&(tempValue>maxValue))//相邻两个数的和大于第二个数并且大于当前值
            {
                end=i;
                maxValue=tempValue;
            }

            else if(tempValue<=a[i])//小的话,从第二个数开始
            {
                begin=i;
                end=i;
                tempValue=a[i];

            }
        }


        //输出最大和的连续子数组的相关信息
        System.out.println("最大子数组和为:"+maxValue+"\n子数组内容为:");
        System.out.println("下标:");
        for(i=begin;i<=end;i++)
            System.out.print(i+"  ");
        System.out.println("\n"+"下标对应数值:");
        for(i=begin;i<=end;i++)
            System.out.print(a[i]+"  ");


    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值