Skip to content

Commit 85caad6

Browse files
committed
Add Maximum Subarray Sum
1 parent acaba91 commit 85caad6

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
fun maximumSubarraySum(nums: List<Int>): Int {
2+
if (nums.isEmpty()) {
3+
return 0
4+
}
5+
// Set the sum variables to negative infinity to ensure negative
6+
// sums can be considered.
7+
var maxSum = Int.MIN_VALUE
8+
var currentSum = Int.MIN_VALUE
9+
// Iterate through the array to find the maximum subarray sum.
10+
for (num in nums) {
11+
// Either add the current number to the existing running sum, or
12+
// start a new subarray at the current number.
13+
currentSum = maxOf(currentSum + num, num)
14+
maxSum = maxOf(maxSum, currentSum)
15+
}
16+
return maxSum
17+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
fun maximumSubarraySumDP(nums: IntArray): Int {
2+
val n = nums.size
3+
if (n == 0) {
4+
return 0
5+
}
6+
val dp = IntArray(n)
7+
// Base case: the maximum subarray sum of an array with just one
8+
// element is that element.
9+
dp[0] = nums[0]
10+
var maxSum = dp[0]
11+
// Populate the rest of the DP array.
12+
for (i in 1 until n) {
13+
// Determine the maximum subarray sum ending at the current
14+
// index.
15+
dp[i] = maxOf(dp[i - 1] + nums[i], nums[i])
16+
maxSum = maxOf(maxSum, dp[i])
17+
}
18+
return maxSum
19+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
fun maximumSubarraySumDPOptimized(nums: IntArray): Int {
2+
val n = nums.size
3+
if (n == 0) {
4+
return 0
5+
}
6+
var currentSum = nums[0]
7+
var maxSum = nums[0]
8+
for (i in 1 until n) {
9+
currentSum = maxOf(nums[i], currentSum + nums[i])
10+
maxSum = maxOf(maxSum, currentSum)
11+
}
12+
return maxSum
13+
}

0 commit comments

Comments
 (0)