Leetcode-053-maximal suborder sum


Maximum suborder sum

Given an integer array nums, find a continuous sub array with the largest sum (the sub array contains at least one element) and return its maximum sum.

See leetcode’s official website for an example.

Source: leetcode
Link: https://leetcode-cn.com/probl…
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Solution 1: dynamic programming

First, initializemaxandsumAll fornumsThe value of the first element of the array, and then traverse the array from bit 2:

  • Whensum <= 0When,sumSet to the value of the current index, that is, discard the previously accumulated value;
  • Whensum > 0When,sumAdd the value of the current index bit and accumulate;
  • Then every time it’s convenientmaxtakemaxandsumThe greater of.

Finally, returnmaxThis is the final result.

public class LeetCode_053 {
    public static int maxSubArray(int[] nums) {
        int max = nums[0], sum = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (sum <= 0) {
                sum = nums[i];
            } else {
                sum = sum + nums[i];
            max = Math.max(max, sum);
        return max;

    public static void main(String[] args) {
        int[] nums = new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4};

[daily message]In busy days, we should learn to find a happy reason for ourselves every day, even if it’s just that the sun is warm and the power is full.

Recommended Today

C serial 20 – exceptions in conversion description

1、 Use formatted output for Strings #include #define BLURB “Authentic imitation!” int D20_1_stringf(void) { printf(“[%2s]\n”, BLURB); printf(“[%24s]\n”, BLURB); printf(“[%24.5s]\n”, BLURB); printf(“[%-24.5s]\n”, BLURB); return 0; } Interpretation: the decimal point is followed by a number, which means that several characters will be output. The one in front of the decimal point indicates how many spaces are […]