微软算法100题03 求子数组的最大和

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

 

思路:使用辅助变量max 记录子数组的最大和,从数组头开始遍历,如果数组元素与之前的总和的sum是负数,则重置sum结果为零,否则将得到的sum值与max比较 如果小于max,则继续计算数组的下一个元素

 

 1 package com.rui.microsoft;
 2 
 3 public class Test03_MaxSubArray {
 4 
 5     public static void main(String[] args) {
 6         int[] array = {1, -2, 3, 10, -4, 7, 2, -5};
 7         System.out.println(findMax(array));
 8     }
 9     
10     private static int findMax(int[] array){
11         int res = 0;
12         int max = res;
13         
14         for(int i = 0; i < array.length; i++){
15             res += array[i];
16             if(res > max){
17                 max = res;
18             }else if(res < 0){
19                 res = 0;
20                 continue;
21             }
22             
23         }
24         
25         return max;
26     }
27 }

 

posted @ 2015-10-20 18:35  蟹粉小笼包  阅读(145)  评论(0编辑  收藏  举报