【算法-Java实现】求连续子数组的最大累加和

【算法-Java实现】求连续子数组的最大累加和

一.问题描述:

1.输入:输入一个字符串,该字符串为一组数据,其中每个数据之间用“,”隔开。(即输入String类型字符串,通过String类的split()方法将字符串转为String类型数组)。

2.输出:输出这个数组的子数组最大累加和。

二.问题解答:

1.若数组为空或者数组的长度为0,直接返回0。

2.若输入的数组中数据没有正数,比如{-6,-2,-3,-5},则最大累加和是数组中的最大值,即-2。

2.思路:初始化max=Integer.MIN_VALUE(以便于调用Math.max()时将数组第一个元素的值设置为当前最大累加和),依次遍历数组,用current记录当前数组的最大累加和。当current<0,将current置为0;当current>0,表示每一次的累加都可能是最大累加和。其中,每一次遍历数组,用max进行跟踪,用Math.max()方法获取current和max的最大值,循环结束返回max即可。

三.算法分析:

1.时间复杂度为O(N),额外空间复杂度为O(1)。

2.注意事项:int max=Integer.MIN_VALUE这一步非常关键,如果初始化为0,会出现问题。比如,当输入全部是负数时{-6,-2,-3,-5}(同上),则会返回0,而不是返回-2。

在JDK中,整型类型是有范围的 -2147483648~2147483647 ( -2^31 — 2^31-1)。

最大值为Integer.MAX_VALUE,即2147483647,最小值为Integer.MIN_VALUE ,即-2147483648。

代码如下

import java.util.*;

public class Solution {
    
    
    /**
     * 求连续子数组的最大和
     * @param array string字符串一维数组 数组
     * @return int整型
     */
	public static void main(String[] args) {
    
    
		Scanner in=new Scanner(System.in);
		String str=in.nextLine();
		String[] array=str.split(",");
		int result=findGreatestSumOfSubArray (array);
		System.out.println(result);
	}
    public static int findGreatestSumOfSubArray (String[] array) {
    
    
        //数组为空或数组的长度为0
    	if(array==null||array.length==0) {
    
    
    		return 0;
    	}
    	int max=Integer.MIN_VALUE;
    	int current=0;
    	for(int i=0;i<array.length;i++) {
    
    
    		current+=Integer.valueOf(array[i].toString());
    		max=Math.max(max, current);
    		current=current<0?0:current;
    	}
    	return max;
    }
}

猜你喜欢

转载自blog.csdn.net/hkdhkdhkd/article/details/109152226
今日推荐