Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# [2501.Longest Square Streak in an Array][title]

## Description
You are given an integer array `nums`. A subsequence of `nums` is called a **square streak** if:

- The length of the subsequence is at least `2`, and
- **after** sorting the subsequence, each element (except the first element) is the **square** of the previous number.

Return the length of the **longest square streak** in `nums`, or return `-1` if there is no **square streak**.

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.

**Example 1:**

```
Input: nums = [4,3,6,16,8,2]
Output: 3
Explanation: Choose the subsequence [4,16,2]. After sorting it, it becomes [2,4,16].
- 4 = 2 * 2.
- 16 = 4 * 4.
Therefore, [4,16,2] is a square streak.
It can be shown that every subsequence of length 4 is not a square streak.
```

**Example 2:**

```
Input: nums = [2,3,5,6,7]
Output: -1
Explanation: There is no square streak in nums so return -1.
```

## 结语

如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-algorithm][me]

[title]: https://leetcode.com/problems/longest-square-streak-in-an-array
[me]: https://github.com/kylesliu/awesome-golang-algorithm
Original file line number Diff line number Diff line change
@@ -1,5 +1,32 @@
package Solution

func Solution(x bool) bool {
return x
import "sort"

func isPerfectSquare(num int) int {
for i := 1; i*i <= num; i++ {
if i*i == num {
return i
}
}
return -1
}

func Solution(nums []int) int {
sort.Ints(nums)
ans := -1
pre := make(map[int]int)
for _, n := range nums {
pre[n] = 1
}
for _, n := range nums {
i := isPerfectSquare(n)
if i == -1 {
continue
}
if l, ok := pre[i]; ok {
pre[n] = l + 1
ans = max(ans, pre[n])
}
}
return ans
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,11 @@ func TestSolution(t *testing.T) {
// 测试用例
cases := []struct {
name string
inputs bool
expect bool
inputs []int
expect int
}{
{"TestCase", true, true},
{"TestCase", true, true},
{"TestCase", false, false},
{"TestCase1", []int{4, 3, 6, 16, 8, 2}, 3},
{"TestCase2", []int{2, 3, 5, 6, 7}, -1},
}

// 开始测试
Expand All @@ -30,10 +29,10 @@ func TestSolution(t *testing.T) {
}
}

// 压力测试
// 压力测试
func BenchmarkSolution(b *testing.B) {
}

// 使用案列
// 使用案列
func ExampleSolution() {
}
Loading