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
the contiguous subarray
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));
}
}
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));
}
}
相关文章推荐
- LeetCode 3 最大不重复子串
- LeetCode-Gas Station-加油站-最大子串算法应用
- Leetcode 3 - 最大不重复子串
- LeetCode | 673. Number of Longest Increasing Subsequence中等偏难题 找寻数组里面最大长度的子串的个数
- Leetcode(3)-找最大子串的长度
- 【Leetcode】寻找数串中连续最大整数和且最大长度的子串
- 【LeetCode】寻找最大长度不重复子串
- leetcode笔记:Maximum Subarray(最大子串和问题)
- 【Leetcode】寻找数串中连续最大整数和且最大长度的子串
- [leetcode]53. Maximum Subarray 最大连续子串python实现【medium】
- 【LeetCode51-60】N皇后,和最大子串,螺旋矩阵,跳跳棋,合并区间,第K个全排列
- LeetCode 53 分治算法,求最大子串
- Leetcode 53 Maximum Subarray 最大子串和
- leetcode_[Python/C++]_3_Longest Substring Without Repeating Characters(不重复子串最大长度)
- Scala Maximum Subarray 最大子串 leetcode 53
- Leetcode—最大无重复子串
- Leetcode刷题记—— 84. Largest Rectangle in Histogram(柱形图中最大矩形面积)
- LeetCode-53-Maximum Subarray(最大和子串)
- leetcode 53. Maximum Subarray 动态规划DP + 最大子串和
- leetcode-java.T005_LongestPalindromicSubstringTotal 给定一个字符串S,找出它的最大的回文子串