The topic is from LeetCode
Other solutions or source code can be accessed: tongji4m3
description
Given an integer array nums, find a continuous sub-array with the largest sum (the sub-array contains at least one element), and return the largest sum.
Example:
输入: [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
Advanced:
If you have already implemented a solution with O(n) complexity, try to use a more subtle divide-and-conquer solution.
Ideas
Traverse from left to right, if it is greater than 0, keep it, otherwise don't. result is judged every moment
detail
Because the sub-array contains at least one element, the initialization cannot be 0, but the minimum value of int
Code
//子数组最少包含一个元素
public int maxSubArray(int[] nums)
{
int N = nums.length;
int result = Integer.MIN_VALUE,temp=0;//look,因为条件是至少包含
for (int i = 0; i < N; i++)
{
temp = temp > 0 ? temp + nums[i] : nums[i];
result = Math.max(result, temp);
}
return result;
}
Complexity analysis
time complexity
O (N) O (N) O ( N )
Space complexity
O (1) O (1) O ( 1 )