0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Ruby] AtCoder過去問 B - Increment Decrement

Last updated at Posted at 2021-09-24

はじめに

AtCoder過去問B問題をRubyで解いてみました。
よろしくお願いします。

問題はこちらから確認してください↓

B - Increment Decrement

まず入力を受け取ります。

n = gets.to_i
s = gets.chars

2行目は文字列を一つずつ区切って、配列にしています。
入力例1でいえば、IIDID["I", "I", "D", "I", "D"]という配列で受け取っています。

次にxを用意して、一回一回のxの結果を記録していく配列x_aryを用意します。この配列には0(xの初期値)を代入しておきます。

n = gets.to_i
s = gets.chars

x = 0
x_ary = [0]

準備は完了したので、配列sをeach文で回してIだったら+1、Dだったら-1という作業を行い、それぞれの結果のxの値をx_aryに記録(追加)していきます。

n = gets.to_i
s = gets.chars

x = 0
x_ary = [0]

s.each do |str|
  if str == "I"
    x_ary << x += 1
  elsif str == "D"
    x_ary << x -= 1
  end
end

puts x_ary.max

最後にx_aryの中で一番大きかった数字をmaxメソッドで出力して完成です。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?