add output for max_sub_array algorithm

This commit is contained in:
Vitor Oliveira 2021-09-03 12:37:05 -07:00 committed by GitHub
parent b7d623a303
commit aecd3739f0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -18,10 +18,8 @@
# 1 <= nums.length <= 3 * 104
# -105 <= nums[i] <= 105
# Dynamic Programming Approach (Kadane's Algorithm) - O(n) Time / O(1) Space
#
# Init max_sum as first element
# Return first element if the array length is 1
# Init current_sum as 0
@ -31,7 +29,6 @@
# max_sum = current_sum if current_sum is greater than max_sum
# Return max_sum
# @param {Integer[]} nums
# @return {Integer}
def max_sub_array(nums)
@ -47,10 +44,23 @@ def max_sub_array(nums)
# iterate through array, reset current_sum to 0 if it ever goes below 0, track max_sum with highest current_sum
nums.each do |num|
current_sum = 0 if current_sum < 0
current_sum += num
max_sum = [max_sum, current_sum].max
end
#return answer
max_sum
end
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print max_sub_array(nums)
# Output: 6
nums = [1]
print max_sub_array(nums)
# Output: 1
nums = [5, 4, -1, 7, 8]
print max_sub_array(nums)
# Output: 23