您的位置:首页 > 编程语言 > Java开发

【LeetCode】 53. Maximum Subarray 最大子序列和

2017-06-04 16:51 429 查看
原题

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array
[-2,1,-3,4,-1,2,1,-5,4]
,

the contiguous subarray
[4,-1,2,1]
has the largest sum =
6
.

思路

1. 最笨的办法

用2个for循环,遍历所有的子序列和,最后得到其中最大的一个

public class Solution {
public int maxSubArray(int[] nums) {
int max = nums[0];
int len = nums.length;
int tempSum = 0;
for(int i = 0 ; i< len ;i ++){
tempSum = nums[i];
if(tempSum >max){
max = tempSum;
}
for(int j = i+1; j< len; j++){
tempSum += nums[j];
if(tempSum >max){
max = tempSum;
}
}
}
return max;
}
}


时间复杂度O(n^2)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 java leetcode