Skip to content

Commit 14ee5f3

Browse files
committed
add kotlin solution for 918. Maximum Sum Circular Subarray
1 parent 39b7ea8 commit 14ee5f3

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
fun maxSubarraySumCircular(nums: IntArray): Int {
3+
if (nums.size == 1) return nums[0]
4+
// max sum
5+
var totalSum = nums[0]
6+
var maxSum = nums[0]
7+
var currentMaxSum = nums[0]
8+
// minSum
9+
var minSum = nums[0]
10+
var currentMinSum = nums[0]
11+
for (i in 1..nums.lastIndex) {
12+
// max sum computation
13+
currentMaxSum = maxOf(nums[i], currentMaxSum + nums[i])
14+
maxSum = maxOf(maxSum, currentMaxSum)
15+
// minSum computation
16+
currentMinSum = minOf(nums[i], currentMinSum + nums[i])
17+
minSum = minOf(minSum, currentMinSum)
18+
totalSum += nums[i]
19+
}
20+
return if (minSum != totalSum) maxOf((totalSum - minSum), maxSum) else maxSum
21+
}
22+
}

0 commit comments

Comments
 (0)