|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 1671. Minimum Number of Removals to Make Mountain Array |
| 4 | +# Hard |
| 5 | +# https://leetcode.com/problems/minimum-number-of-removals-to-make-mountain-array |
| 6 | + |
| 7 | +=begin |
| 8 | +You may recall that an array arr is a mountain array if and only if: |
| 9 | +* arr.length >= 3 |
| 10 | +* There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that: |
| 11 | + * arr[0] < arr[1] < ... < arr[i - 1] < arr[i] |
| 12 | + * arr[i] > arr[i + 1] > ... > arr[arr.length - 1] |
| 13 | +Given an integer array nums, return the minimum number of elements to remove to make nums a mountain array. |
| 14 | +
|
| 15 | +Example 1: |
| 16 | +Input: nums = [1,3,1] |
| 17 | +Output: 0 |
| 18 | +Explanation: The array itself is a mountain array so we do not need to remove any elements. |
| 19 | +
|
| 20 | +Example 2: |
| 21 | +Input: nums = [2,1,1,5,6,2,3,1] |
| 22 | +Output: 3 |
| 23 | +Explanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1]. |
| 24 | +
|
| 25 | +Constraints: |
| 26 | +* 3 <= nums.length <= 1000 |
| 27 | +* 1 <= nums[i] <= 109 |
| 28 | +* It is guaranteed that you can make a mountain array out of nums. |
| 29 | +=end |
| 30 | + |
| 31 | +# @param {Integer[]} nums |
| 32 | +# @return {Integer} |
| 33 | +def minimum_mountain_removals(nums) |
| 34 | + n = nums.size |
| 35 | + inc = Array.new(n, 1) |
| 36 | + dec = Array.new(n, 1) |
| 37 | + |
| 38 | + (1...n).each do |i| |
| 39 | + (0...i).each do |j| |
| 40 | + inc[i] = [inc[i], inc[j] + 1].max if nums[i] > nums[j] |
| 41 | + end |
| 42 | + end |
| 43 | + |
| 44 | + (n - 2).downto(0) do |i| |
| 45 | + (i + 1...n).each do |j| |
| 46 | + dec[i] = [dec[i], dec[j] + 1].max if nums[i] > nums[j] |
| 47 | + end |
| 48 | + end |
| 49 | + |
| 50 | + max_mountain = 0 |
| 51 | + (1...n - 1).each do |i| |
| 52 | + if inc[i] > 1 && dec[i] > 1 |
| 53 | + max_mountain = [max_mountain, inc[i] + dec[i] - 1].max |
| 54 | + end |
| 55 | + end |
| 56 | + |
| 57 | + n - max_mountain |
| 58 | +end |
| 59 | + |
| 60 | +# ********************# |
| 61 | +# TEST # |
| 62 | +# ********************# |
| 63 | + |
| 64 | +require "test/unit" |
| 65 | +class Test_minimum_mountain_removals < Test::Unit::TestCase |
| 66 | + def test_ |
| 67 | + assert_equal 0, minimum_mountain_removals([1, 3, 1]) |
| 68 | + assert_equal 3, minimum_mountain_removals([2, 1, 1, 5, 6, 2, 3, 1]) |
| 69 | + end |
| 70 | +end |
0 commit comments