Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 2501. Longest Square Streak in an Array

Rain Hu

2501. Longest Square Streak in an Array


一、題目

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

Example 1:

Example 2:

Constraints:


二、分析

三、解題

1. DP

int longestSquareStreak(vector<int>& nums) {
    vector<int> dp(nums.size(), 1);
    unordered_map<int,int> map;
    sort(nums.begin(), nums.end());
    int res = -1;
    for (int i = 0; i < nums.size(); i++) {
        int target = sqrt(nums[i]);
        if (target * target == nums[i]) {
            if (map.count(target)) {
                dp[i] = dp[map[target]] + 1;
                res = max(dp[i], res);
            }    
        }
        map[nums[i]] = i;
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 70. Climbing Stairs
Next
[LeetCode] 2500. Delete Greatest Value in Each Row