求一个数组中,子数组最大和

版权声明:禁止侵权,打击盗版! https://blog.csdn.net/ChenGX1996/article/details/82415283

例如:

[-1 2 3 -4 5 6]

最大子数组和为5+6 = 11;

由用户自定义输入数组;

import java.io.*;

//一个数组中有n个元素,求连续子数组最大的和,例如:[-2,1,2],最大的连续子数组为[1,2],和为3;
public class Mmd {
    public static int getLarge(int[] array){
        int max = 0;
        int temp = 0;
        /**
         * 创建两个变量,一个为第一次找到的最大子数组和,
         * 一个为后续子数组和,循环判断大小
         */
        for(int i=0;i<array.length;i++){
            if(array[i] >= 0){
                temp+=array[i];
                continue;
            }
            if(temp > max){
                max = temp;
                temp = 0;
            }
        }
        max = max>temp?max:temp;
        return max;
    }
    public static int getInt(String[] array){
        //先将String类数组转换成int类数组
    	if(array.length == 0) {
    		return 0;
    	}
        int[] result = new int[array.length];
        //如果输入的不是整数数组,则提示用户!
       try {
		 for(int i=0;i<array.length;i++){
            //将String类型元素转换为int类型
            result[i] = Integer.parseInt(array[i]);
        }
	} catch (Exception e) {
		System.out.println("整数数组输入有误!"+e);
	}
        return getLarge(result);
    }
    public static void main(String[] args){
        System.out.println("请输入一个数组(用空格分开):");
        Scanner in = new Scanner(System.in);
        String str = null;
        if(in.hasNextLine()){
            str = in.nextLine();
        }
        in.close();
        //将字符串拆分成一个String类数组
        String[] array = str.split(" ");
        System.out.println("该数组连续子数组最大的和为:"+getInt(array));
    }
}

猜你喜欢

转载自blog.csdn.net/ChenGX1996/article/details/82415283
今日推荐