o1-mini-2024-09-12· OpenAI
WildChat-4.8M (AI2)
You are given an integer array nums. A subsequence of nums is called a square streak if:…
- User
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.
Constraints: 2 <= nums.length <= 10^5 2 <= nums[i] <= 10^5
Write code in C++. The first 2 lines of code are: #include <bits/stdc++.h> using namespace std; Use the following concepts in your code: array, hash table, binary search, dynamic programming, sorting.
- Assistant
#include <bits/stdc++.h> using namespace std; class Solution { public: int longestSquareStreak(vector<int>& nums) { // Create a boolean vector to mark the presence of each number vector<bool> present(100001, false); for(auto x: nums){ present[x] = true; } // Extract and sort the unique numbers vector<int> sorted_nums; for(int x = 2; x <= 100000; x++) { if(present[x]) sorted_nums.push_back(x); } // Initialize a DP array where dp[x] represents the longest streak ending with x vector<int> dp(100001, 1); int max_len = 1; // Iterate through the sorted numbers to build the longest streak for(auto x: sorted_nums){ // Calculate the integer square root of x int y = floor(sqrt((double)x)); // Check if y^2 equals x and y is present in the array if( (long long)y * y == x && y >= 2 && present[y]){ dp[x] = dp[y] + 1; max_len = max(max_len, dp[x]); } // If not, dp[x] remains 1 } // Return the maximum streak length if it's at least 2, otherwise -1 return max_len >= 2 ? max_len : -1; } }; // Example usage: int main(){ Solution solution; // Example 1 vector<int> nums1 = {4,3,6,16,8,2}; cout << solution.longestSquareStreak(nums1) << endl; // Output: 3 // Example 2 vector<int> nums2 = {2,3,5,6,7}; cout << solution.longestSquareStreak(nums2) << endl; // Output: -1 return 0; }