Skip to content

Commit 731e46c

Browse files
committed
918 programming added
1 parent 5a5f0b9 commit 731e46c

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

programming-py/918.py

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
def maxCircularSubArray(nums):
2+
"""
3+
using kadane approach
4+
maximum circular sub array = max(maxiumNonCircularSubArray, SumOfWholeArray - mimimumNonCircularSubArray)
5+
in case if all the elements of circular subarray is negative, max element of the list is the answer
6+
"""
7+
max_so_far = min_so_far = max_here = min_here = nums[0]
8+
negative_so_far = True
9+
for num in nums[1:]:
10+
if num >= 0:
11+
negative_so_far = False
12+
max_here, min_here = max(num, max_here+num), min(num, min_here + num)
13+
max_so_far, min_so_far = max(
14+
max_so_far, max_here), min(min_so_far, min_here)
15+
if negative_so_far:
16+
return max(nums)
17+
return max(max_so_far, sum(nums)-min_so_far)
18+
19+
20+
# test below
21+
print(maxCircularSubArray([1, -2, 3, -2]))
22+
print(maxCircularSubArray([5, -3, 5]))
23+
print(maxCircularSubArray([-3, -2, -3]))

0 commit comments

Comments
 (0)