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アルゴリズム(Array Partition I)

Posted at

問題

Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum.

Example 1:

Input: nums = [1,4,3,2]
Output: 4
Explanation: All possible pairings (ignoring the ordering of elements) are:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
So the maximum possible sum is 4.
Example 2:

Input: nums = [6,2,6,5,1,2]
Output: 9
Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.

Constraints:

1 <= n <= 104
nums.length == 2 * n
-104 <= nums[i] <= 104

私の回答

def array_pair_sum(nums)
    array = nums.sort.each_slice(2).to_a
    small_array = []
    array.each do |ary|
        small_array << ary.min
    end
    return small_array.sum
end

なんかごちゃっとしている気もするけど無事Accepted!!

やったことを書いていきます。

この問題は大きな配列に入っている数値を小さい数値順に並べ直し、2つずつペアにしていきますが
解き方に関しては数学の話なので省略して、コードについて以下に書いていきます。

まずここ

    array = nums.sort.each_slice(2).to_a

小さい順番に並び替えます。

    nums = [2, 4, 1, 3]
    array = nums.sort # => [1, 2, 3, 4]

2個ずつ数値の入った配列へsliceしていきます。

    array = nums.sort.each_slice(2).to_a # => [[1, 2], [3, 4]]

空の配列を作り、そこに上で作った小さな配列のうち小さい方の数値を入れていきます。

    small_array = []
    array.each do |ary|
        small_array << ary.min
    end

最後にそれらを足したものを返り値として返して終了。

    return small_array.sum

無事Accepted!!
しかしなんだかごちゃごちゃしているような気がする。
もっと綺麗な方法がありそう。

0
0
0

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?