|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 2501. Longest Square Streak in an Array |
| 4 | +# Medium |
| 5 | +# https://leetcode.com/problems/longest-square-streak-in-an-array |
| 6 | + |
| 7 | +=begin |
| 8 | +You are given an integer array nums. A subsequence of nums is called a square streak if: |
| 9 | +* The length of the subsequence is at least 2, and |
| 10 | +* after sorting the subsequence, each element (except the first element) is the square of the previous number. |
| 11 | +Return the length of the longest square streak in nums, or return -1 if there is no square streak. |
| 12 | +A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. |
| 13 | +
|
| 14 | +Example 1: |
| 15 | +Input: nums = [4,3,6,16,8,2] |
| 16 | +Output: 3 |
| 17 | +Explanation: Choose the subsequence [4,16,2]. After sorting it, it becomes [2,4,16]. |
| 18 | +- 4 = 2 * 2. |
| 19 | +- 16 = 4 * 4. |
| 20 | +Therefore, [4,16,2] is a square streak. |
| 21 | +It can be shown that every subsequence of length 4 is not a square streak. |
| 22 | +
|
| 23 | +Example 2: |
| 24 | +Input: nums = [2,3,5,6,7] |
| 25 | +Output: -1 |
| 26 | +Explanation: There is no square streak in nums so return -1. |
| 27 | +
|
| 28 | +Constraints: |
| 29 | +* 2 <= nums.length <= 105 |
| 30 | +* 2 <= nums[i] <= 105 |
| 31 | +=end |
| 32 | + |
| 33 | +# @param {Integer[]} nums |
| 34 | +# @return {Integer} |
| 35 | +def longest_square_streak(nums) |
| 36 | + nums = nums.uniq.sort |
| 37 | + num_set = nums.to_set |
| 38 | + max_length = 0 |
| 39 | + |
| 40 | + nums.each do |num| |
| 41 | + length = 0 |
| 42 | + current = num |
| 43 | + |
| 44 | + while num_set.include?(current) |
| 45 | + length += 1 |
| 46 | + current = current**2 |
| 47 | + end |
| 48 | + |
| 49 | + if length > 1 |
| 50 | + max_length = [max_length, length].max |
| 51 | + end |
| 52 | + end |
| 53 | + |
| 54 | + max_length > 1 ? max_length : -1 |
| 55 | +end |
| 56 | + |
| 57 | +# ********************# |
| 58 | +# TEST # |
| 59 | +# ********************# |
| 60 | + |
| 61 | +require "test/unit" |
| 62 | +class Test_longest_square_streak < Test::Unit::TestCase |
| 63 | + def test_ |
| 64 | + assert_equal 3, longest_square_streak([4, 3, 6, 16, 8, 2]) |
| 65 | + assert_equal(-1, longest_square_streak([2, 3, 5, 6, 7])) |
| 66 | + end |
| 67 | +end |
0 commit comments