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:
- When
sum <= 0
When,sumSet to the value of the current index, that is, discard the previously accumulated value;- When
sum > 0
When,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};
System.out.println(maxSubArray(nums));
}
}
[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.