`
snake_hand
  • 浏览: 574493 次
社区版块
存档分类
最新评论

一个整形数组,数组里有正数也有负数。 数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和,求所有子数组的和的最大值,要求时间复杂度为O(n)。

 
阅读更多

一个整形数组,数组里有正数也有负数。
数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和,求所有子数组的和的最大值,要求时间复杂度为O(n)。

例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,那么最大的子数组为3, 10, -4, 7, 2,因此输出为该子数组的和18

由于本人C\C++水平有限,所以使用java语言实现。

思路:从数组的后面排除小于0或者累加小于0的,用max记录被排除的子数组的和的最大值。

/***
 * @author lingxiasandu
 */
public class Test {

    public static void main(String[] args) {
        
        int[] a = {1, -2, 3, 10, -4, 7, 2, -5};
        int max = MaxSum(a);
        System.out.println(max);
    }
    
    /***
     * @param a 源数组
     * @return 返回子数组和的最大值
     */
    public static int MaxSum(int[] a){
        int sum = 0;
        int max = 0;
        for(int i=0;i<a.length;i++){
            sum = sum + a[a.length-i-1];
            if(a[a.length-i-1] >= 0){
               if(max < sum){
                  max = sum ;
                }
            }
            if(sum < 0){
                 sum = 0;
             }
        }
        return max;
    }

}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics