最大子串问题

在刷题的时候 碰到了最大子串的问题,第一时间没有想出来,看了别人的解答发现很简单 写下来记录一哈

题目如下:

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.

解题思路如下:
首先确定一个最大值 max ,设为一个特别小的值,因为最大子串的值不确定 但是肯定大于这个值.
再定义一个总和值 sum,记录遍历子串的和.
遍历这个数组,如果sum的值小于0,则sum就等于遍历到的这个值,如果sum的值大于0,那么sum的值等于sum+遍历到的值.同时判断如果这个sum的值大于最大值max,则max就等于当前的sum。
(因为如果sum小于0了,那么证明这个当前的子串的累加值就是负数的,再和遍历到的这个值相加 也不可能是最大的子串值了,所以就舍弃前面的子串 从当前的遍历值开始 当做子串。)

代码如下:

public static int maxSubArray(int[] nums) {
    	int sum = 0;
    	int max = Integer.MIN_VALUE;
    	for(int i:nums){
    		if(sum > 0){
    			sum += i;
    		}else{
    			sum = i;
    		}
    		if(sum > max){
    			max = sum;
    		}
    	}
    	return max;
    }
发布了19 篇原创文章 · 获赞 0 · 访问量 295

猜你喜欢

转载自blog.csdn.net/XXuan_/article/details/93372455