题目描述
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
样例
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.
思路分析
同 剑指offer(30)题,但leetcode的样例里会有一个超大的数组,直接使复杂度O(n^2)的运行时间溢出,参考了一下讨论区的答案 用max函数比较做的
代码
public static int maxSubArray(int[] A) { int maxSoFar=A[0], maxEndingHere=A[0]; for (int i=1;i<A.length;++i){ maxEndingHere= Math.max(maxEndingHere+A[i],A[i]); maxSoFar=Math.max(maxSoFar, maxEndingHere); } return maxSoFar; }
结果