Advertisement
Iam_Sandeep

Maximum subarray sum Kadane

Jul 28th, 2022
894
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. class Solution:
  2.     def maxSubArray(self, a: List[int]) -> int:
  3.         cur,maxi=a[0],a[0]
  4.         for i in a[1:]:
  5.             cur = i + (cur if cur>0 else 0)
  6.             maxi = max(maxi,cur)
  7.         return maxi
  8. '''
  9. Analysis of this problem:
  10. Apparently, this is a optimization problem, which can be usually solved by DP. So when it comes to DP, the first thing for us to figure out is the format of the sub problem(or the state of each sub problem). The format of the sub problem can be helpful when we are trying to come up with the recursive relation.
  11.  
  12. At first, I think the sub problem should look like: maxSubArray(int A[], int i, int j), which means the maxSubArray for A[i: j]. In this way, our goal is to figure out what maxSubArray(A, 0, A.length - 1) is. However, if we define the format of the sub problem in this way, it's hard to find the connection from the sub problem to the original problem(at least for me). In other words, I can't find a way to divided the original problem into the sub problems and use the solutions of the sub problems to somehow create the solution of the original one.
  13.  
  14. So I change the format of the sub problem into something like: maxSubArray(int A[], int i), which means the maxSubArray for A[0:i ] which must has A[i] as the end element. Note that now the sub problem's format is less flexible and less powerful than the previous one because there's a limitation that A[i] should be contained in that sequence and we have to keep track of each solution of the sub problem to update the global optimal value. However, now the connect between the sub problem & the original one becomes clearer:
  15.  
  16. maxSubArray(A, i) = maxSubArray(A, i - 1) > 0 ? maxSubArray(A, i - 1) : 0 + A[i];
  17. And here's the code
  18. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement