File tree Expand file tree Collapse file tree 3 files changed +49
-0
lines changed
kotlin/Dynamic Programming Expand file tree Collapse file tree 3 files changed +49
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments