[JAVA算法]求子数组的最大和

每日一算法,学习JAVA

前几天面试过程中遇到过类似求子叔祖的最大和。这是网上找的一道题。借用一下。

        输入一个整形数组,数组里有正数也有负数。
        数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。
        求所有子数组的和的最大值。要求时间复杂度为O(n)。
        例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,
        因此输出为该子数组的和18。

package com.java.test.arithmetic;

/**
 * 求子数组的最大和
 * @author LIUYONG
 * 2011-8-01
 */
public class RecursiveTestArrayMaxSum {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int[] a=new int[]{1, -2, 3, 10, -4, 7, 2, -5};
        System.out.println(Maxsub(a));
    }
   

    public static int Maxsub(int[] a) {
 
        int maxSum = a[0]; //最大连续数字和。默认为第一个数
        int temp = 0;
       
        for (int i = 0; i <a.length; ++i) {
            temp += a[i]; //累加
            if (temp > maxSum){//如果累加结果大于最大数字和
                maxSum = temp;     //将累加结果附值给最大数字和
            }
            else if(temp < 0){//累加结果小于0
                temp = 0;    //累加结果设置为0
            }
        }
        return maxSum;
    }



}
原文地址:https://www.cnblogs.com/liuyongcn/p/2124282.html