Given an integer array nums
, find the contiguous subarray (containing at least one number) which have the largest sum and return its sum.
Example:
Input: [ -2,1,-3,4,-1,2,1,-5,46Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you had figured out the O (n) solution, try coding another solution using the divide and conquer approach, WHI CH is more subtle.
Test instructions
To find the largest subarray and
Ideas:
One-dimensional DP
Principle: Any number plus negative is definitely smaller than the original value
Dp[i] Indicates the maximum value that can be taken by the first element
Dp[i] = dp[i-1] >0? DP[I-1] + num[i]: num[i]
Code:
1 classSolution {2 Public intMaxsubarray (int[] nums) {3 int[] DP =New int[nums.length];4Dp[0] = nums[0];5 intMaxresult = Nums[0];6 7 for(inti = 1; i < nums.length; i++){8Dp[i] = Dp[i-1] > 0? DP[I-1] +Nums[i]: nums[i];9Maxresult =Math.max (Maxresult, dp[i]);Ten } One returnMaxresult; A } -}
[Leetcode]53. Maximum Subarray maximum sub-array and