Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #used to find the subarray whose sum of elements
- # is the highest - via sliding windows
- # returns the max_sum and index of beginning of the subarray
- def maxsubarray(a,size):
- max_sum = 0
- window_sum = 0
- window_start = 0
- index_win = 0
- n = len(a)
- for i in range(0,n,1):
- window_sum += a[i]
- if (i >= size - 1):
- if max_sum < window_sum:
- max_sum = window_sum
- index_win = window_start
- window_sum -= a[window_start]
- window_start += 1
- return (max_sum,index_win)
- def solution(A,K,L):
- N = len(A)
- if N == K+L:
- sum = 0
- for element in A:
- sum += element
- return sum
- else:
- first = max(K,L)
- second = min(K,L)
- first_sum, index = maxsubarray(A,first)
- second_sum = max(maxsubarray(A[:index],second)[0],maxsubarray(A[(index + first):],second)[0])
- return (first_sum + second_sum) % 1000000007
- a = [6,1,4,6,3,2,7,4]
- print(solution(a,3,2))
Advertisement
Add Comment
Please, Sign In to add comment