输入一个整型数组,数组里有正数,也有负数。求所有子数组的和的最大值

题目:

输入一个整型数组,数组里有正数,也有负数。

数组中一个或连续的多个整数组成一个子数组。

求所有子数组的和的最大值。要求时间复杂度为 O(n)。

解答:

 1 public class Solution {
 2     public static void main(String[] args) {
 3         int[] arr = {1,-2,3,10,-4,7,2,-5};
 4         System.out.println(maxSub(arr));
 5     }
 6 
 7     private static int maxSub(int[] arr) {
 8 
 9         int max = 0;
10         
11         int n = arr.length;
12         int sum = 0;
13         for(int i = 0; i < n; i++) {
14             sum = sum + arr[i];
15             if(sum > max) {
16                 max = sum;
17             } else if(sum < 0) {
18                 sum = 0;
19             }
20         }
21 
22         return max;
23     }
24 }
原文地址:https://www.cnblogs.com/wylwyl/p/10373947.html