题目描述
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;
}结果

本文介绍了一种求解最大子数组和问题的有效算法。针对给定整数数组,通过迭代方式找出连续子数组的最大和,并附带示例说明。算法采用动态规划思想,避免了时间复杂度过高的问题。
Maximum Subarray&spm=1001.2101.3001.5002&articleId=80659182&d=1&t=3&u=a0990a6155234f7c91a05960bae1f5f7)
592

被折叠的 条评论
为什么被折叠?



