您的位置:首页 > 其它

lintcode :最大子数组

2015-10-17 13:28 190 查看
题目:

最大子数组

给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。

样例

给出数组
[−2,2,−3,4,−1,2,1,−5,3]
,符合要求的子数组为
[4,−1,2,1]
,其最大和为
6


注意

子数组最少包含一个数

挑战

要求时间复杂度为O(n)

解题:

通过率37%,一定是暴力,时间复杂度O(N3)刷出来的成绩。。。

动态规划求解,维基百科

下面程序半个暴力吧,时间复杂度O(n2)

Java程序:

public class Solution {
/**
* @param nums: A list of integers
* @return: A integer indicate the sum of max subarray
*/
public int maxSubArray(ArrayList<Integer> nums) {
// write your code
int max_ending_here = nums.get(0);
int max_so_far = nums.get(0);
for( int i =1 ;i<nums.size(); i++) {
max_ending_here = Math.max( nums.get(i) , nums.get(i) + max_ending_here );
max_so_far = Math.max( max_so_far, max_ending_here);
}
return max_so_far;

}
}


View Code
总耗时: 1539 ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: