Find the contiguous subarray within an array (containing at least one number) which has the largest sum.For example, given the array [−2,1,−3,4,−1,2,1,−5,4],the contiguous subarray [4,−1,2,1] has the largest sum = 6.
Thought difficulty: 99; operation difficulty: 50. A strong proof that thinking is greater than action. This is a very classic dynamic planning question. We also use this idea in other dynamic planning questions. Later we will call it the "local optimal and global optimal solution" method. For more information about DP, see jump game and jump Game II.
The basic idea is as follows. In each step, we maintain two variables. One is global optimization, which is the optimal solution for the current element. The other is local optimization, it is the optimal solution that must contain the current element. Next, let's talk about the recursive formula of Dynamic Planning (this is the most important step in dynamic planning. When the recursive formula comes out, basically the code framework will come out ). If we know the global [I] (global optimal) and local [I] (local optimal) of step I, the expression in step I + 1 is:
Local [I + 1] = math. max (A [I], local [I] + A [I]), that is, the local optimum must contain the current element, otherwise, it is the local optimal [I] + current element a [I] in the previous step (because local [I] must contain the I element, it does not violate the conditions ), however, if the local [I] is negative, it would be better not to add it as needed. Otherwise, a [I] is used directly;
Global [I + 1] = math (local [I + 1], global [I]), with the local optimum of the current step, the global optimization is the current local optimization or the original global optimization (all situations will be covered, because if the optimal solution does not contain the current element, it will be maintained in the Global Optimum. if it contains the current element, it is the local optimum ).
Next, let's analyze the complexity. In terms of time, we only need to scan the array once, so the time complexity is O (n ). In space, we can see that the expression only needs to use the local [I] and global [I] in the previous step to get the next result, so we can use a variable to iterate this result in implementation. We don't need to use an array, that is, as implemented in the program. Therefore, the space complexity is two variables (local and global ), that is, O (2) = O (1)
1 public class Solution { 2 public int maxSubArray(int[] A) { 3 if (A.length == 0 || A == null) return 0; 4 int GlobalLarge = A[0]; 5 int CurrLarge = A[0]; 6 for (int i=1; i<A.length; i++) { 7 CurrLarge = Math.max(A[i], CurrLarge+A[i]); 8 GlobalLarge = Math.max(CurrLarge, GlobalLarge); 9 }10 return GlobalLarge;11 }12 }
Leetcode: Maximum subarray