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

Leetcode刷题记——53. Maximum Subarray(最大子串)

2017-02-23 17:24 387 查看
一、题目叙述:

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
.

click to show more practice.

Subscribe to see which companies asked this question.

二、解题思路:

easy题!感觉算比较经典的求最大字串和的题思路如下:

(1)首先找出数组中最大的值(以防数组中全是负数,越加越小)作为max值。

(2)遍历数组,用sum来计算子串和 1、若子串和为负数,那么将sum值重置为0(因为负数必定带来的是缩小和的影响),继续向后遍历数组;2、若sum值不小于0,比较其与max值的大小,若大于,更新max值,继续遍历数组。

三、源码:

public class Solution
{
public int maxSubArray(int[] nums)
{
int max = Integer.MIN_VALUE;
int sum = 0;
for (int i = 0; i < nums.length; i ++)
{
if (max < nums[i]) max = nums[i];
}
for (int i = 0; i < nums.length; i++)
{
sum += nums[i];
if (sum < 0) sum = 0;
else
{
if (sum > max) max = sum;
}
}
return max;
}
public static void main(String args[])
{

// int[] digits = {0};
Solution solution = new Solution();
int[] abc = {2};
// int[] b = {2,3,4};
// for(int i = 0; i < abc.length; i ++)

System.out.print(solution.maxSubArray(abc));

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