标签:style blog color io ar for div sp log
题目:输入一个整型数组,数组里有正数也有负数。数组中一个或连续的多个整数组成一个子数组。求所有字数组的和的最大值。要求时间复杂度为O(n).
public class Main { public static int getMaxSum(int[] array) throws Exception{ if (array == null && array.length == 0) { throw new Exception() ; } int maxSum = array[0]; int tempSum = maxSum; for (int i = 1; i < array.length; i++) { if (tempSum < 0) { tempSum = array[i]; } else { tempSum += array[i]; } if (tempSum >= maxSum) { maxSum = tempSum; } } return maxSum; } public static void main(String[] args) { int[] array = {-1, -2, -3, -10, -4, -5, -2, -5}; try { System.out.println(getMaxSum(array)); } catch (Exception e) { e.printStackTrace(); } } }
标签:style blog color io ar for div sp log
原文地址:http://www.cnblogs.com/wanghui390/p/3965708.html