Advertisement
skb50bd

Maximum_Subarray_Problem [Kadane's Algorithm]

Sep 28th, 2016
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.92 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. '''
  4. Author: Shakib Haris
  5. Problem: Maximum Subarray Problem
  6. Solution: Kadane's Algorithm // O(n)
  7. Input: The Change(s) of Price, not the Prices
  8. Output: Maximum Subarray
  9. '''
  10.  
  11. def kadane (A):
  12.     maxEndingHere = A[0]
  13.     maxSoFar = A[0]
  14.     lenA = len(A)
  15.     start = end = tStart = 0
  16.  
  17.     for i in range(1, lenA):
  18.         maxEndingHere += A[i]
  19.  
  20.         if maxEndingHere < A[i]:
  21.             maxEndingHere = A[i]
  22.             tStart = i
  23.  
  24.         if maxSoFar < maxEndingHere:
  25.             maxSoFar = maxEndingHere
  26.             start = tStart
  27.             end = i
  28.  
  29.     return start, end, maxSoFar
  30.  
  31.  
  32. def display(A):
  33.     for item in A:
  34.         print("%d " %item, end = "")
  35.     print("")
  36.  
  37.  
  38.  
  39. A = [int(x) for x in input().split()]
  40. print("Original Array: ", end = "")
  41. display(A)
  42. start, end, maxSum = kadane(A)
  43. print("Max Sum: %d\nSub-array: " %maxSum, end = "")
  44. display(A[start:end + 1])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement