Advertisement
skb50bd

Maximum_Subarray_Problem [DivideAndConquer]

Sep 28th, 2016
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.55 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. '''
  4. Author: Shakib Haris
  5. Problem: Maximum Subarray Problem
  6. Solution: Divide and Conquer // O(n lg n)
  7. Input: The Change(s) of Price, not the Prices
  8. Output: Maximum Subarray
  9. '''
  10.  
  11.  
  12.  
  13. def findMaxCrossingSubarray(A, lo, mid, hi):
  14.     leftSum = float('-inf')
  15.     Sum = 0
  16.     for i in range(mid, lo - 1, -1):
  17.         Sum += A[i]
  18.         if Sum > leftSum:
  19.             leftSum = Sum
  20.             maxLeft = i
  21.     rightSum = float('-inf')
  22.     Sum = 0
  23.     for i in range(mid + 1, hi + 1):
  24.         Sum += A[i]
  25.         if Sum > rightSum:
  26.             rightSum = Sum
  27.             maxRight = i
  28.  
  29.     return maxLeft, maxRight, leftSum + rightSum
  30.  
  31.  
  32.  
  33. def findMaxSubarray(A, lo, hi):
  34.     if lo == hi:
  35.         return lo, hi, A[lo]
  36.     else:
  37.         mid = (lo + hi) // 2
  38.         leftLo, leftHi, leftSum = findMaxSubarray(A, lo, mid)
  39.         rightLo, rightHi, rightSum = findMaxSubarray(A, mid + 1, hi)
  40.         crossLo, crossHi, crossSum = findMaxCrossingSubarray(A, lo, mid, hi)
  41.  
  42.     if leftSum >= rightSum and leftSum >= crossSum:
  43.         return leftLo, leftHi, leftSum
  44.     elif rightSum >= leftSum and rightSum >= crossSum:
  45.         return rightLo, rightHi, rightSum
  46.     else:
  47.         return crossLo, crossHi, crossSum
  48.  
  49.  
  50.  
  51. def display(A):
  52.     for item in A:
  53.         print("%d " %item, end = "")
  54.     print("")
  55.  
  56.  
  57.  
  58. A = [int(x) for x in input().split()]
  59. print("Original Array: ", end = "")
  60. display(A)
  61. start, end, maxSum = findMaxSubarray(A, 0, len(A) - 1)
  62. print("Max Sum: %d\nSub-array: " %maxSum, end = "")
  63. display(A[start:end + 1])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement