Given an array, find the sum of the largest consecutive subsequences in the array

王林
Release: 2023-02-27 21:58:01
Original
3218 people have browsed it

Given an array, find the sum of the largest consecutive subsequences in the array

The time complexity is O(n)

You only need to go through the array once, but you need to deeply understand the essential characteristics of this array. That is, the method of dynamic programming.

First set two variables, thisSum and maxSum. Among them, thisSum represents the sum of elements reaching the current position; maxSum represents the maximum sum of consecutive subsequences reaching the current position.

Note: If thisSum is negative, set it to 0 directly; if thisSum is greater than maxSum, set maxSum to the value of thisSum.

public static int maxSubArray(int[] nums)
    {
        int length = nums.length;
        if(length <= 0)
            return 0;
        int CurSum = 0;
        int max = Integer.MIN_VALUE;
        for(int i = 0; i < length; i++)
        {
            if(CurSum <= 0)     //当当前的和小于等于0,那么就给其置为当前元素的值
                CurSum = nums[i];
            else
                CurSum += nums[i];
            if(CurSum > max)
                max = CurSum;
        }
        return max;
    }
Copy after login

Recommended tutorial: PHP tutorial

The above is the detailed content of Given an array, find the sum of the largest consecutive subsequences in the array. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!