Skip to content

Commit ad6b77e

Browse files
committed
2024-07-16 v. 6.1.7: added "53. Maximum Subarray"
1 parent a79cf77 commit ad6b77e

File tree

4 files changed

+30
-1
lines changed

4 files changed

+30
-1
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -482,3 +482,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/).
482482
| 46. Permutations | [Link](https://leetcode.com/problems/permutations/) | [Link](./lib/medium/46_permutations.rb) |
483483
| 48. Rotate Image | [Link](https://leetcode.com/problems/rotate-image/) | [Link](./lib/medium/48_rotate_image.rb) |
484484
| 49. Group Anagrams | [Link](https://leetcode.com/problems/group-anagrams/) | [Link](./lib/medium/49_group_anagrams.rb) |
485+
| 53. Maximum Subarray | [Link](https://leetcode.com/problems/maximum-subarray/) | [Link](./lib/medium/53_maximum_subarray.rb) |

leetcode-ruby.gemspec

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ require 'English'
55
::Gem::Specification.new do |s|
66
s.required_ruby_version = '>= 3.0'
77
s.name = 'leetcode-ruby'
8-
s.version = '6.1.6'
8+
s.version = '6.1.7'
99
s.license = 'MIT'
1010
s.files = ::Dir['lib/**/*.rb'] + %w[bin/leetcode-ruby README.md LICENSE]
1111
s.executable = 'leetcode-ruby'

lib/medium/53_maximum_subarray.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# frozen_string_literal: true
2+
3+
# https://leetcode.com/problems/maximum-subarray/
4+
# @param {Integer[]} nums
5+
# @return {Integer}
6+
def max_sub_array(nums)
7+
max = nums.first
8+
curr = max
9+
nums.drop(1).each do |num|
10+
curr = [curr + num, num].max
11+
max = [curr, max].max
12+
end
13+
14+
max
15+
end
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# frozen_string_literal: true
2+
3+
require_relative '../test_helper'
4+
require_relative '../../lib/medium/53_maximum_subarray'
5+
require 'minitest/autorun'
6+
7+
class MaximumSubarrayTest < ::Minitest::Test
8+
def test_default
9+
assert_equal(6, max_sub_array([-2, 1, -3, 4, -1, 2, 1, -5, 4]))
10+
assert_equal(1, max_sub_array([1]))
11+
assert_equal(23, max_sub_array([5, 4, -1, 7, 8]))
12+
end
13+
end

0 commit comments

Comments
 (0)