2501. Longest Square Streak in an Array #759
-
Topics: You are given an integer array
Return the length of the longest square streak in 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:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to identify the longest square streak in the Here's the solution approach:
Let's implement this solution in PHP: 2501. Longest Square Streak in an Array <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function longestSquareStreak($nums) {
// Step 1: Sort the array for ordered subsequences
sort($nums);
// Step 2: Create a set for quick existence checks
$numSet = array_flip($nums); // Using array keys as a set
$maxStreak = 0;
// Step 3: Iterate over each number in the sorted array
foreach ($nums as $num) {
$currentStreak = 1;
$currentNum = $num;
// Check for the square streak
while (isset($numSet[$currentNum * $currentNum])) {
$currentNum = $currentNum * $currentNum;
$currentStreak++;
}
// Update max streak if we found a longer one
if ($currentStreak >= 2) {
$maxStreak = max($maxStreak, $currentStreak);
}
}
// Step 4: Return result
return $maxStreak >= 2 ? $maxStreak : -1;
}
// Test cases
$nums1 = [4, 3, 6, 16, 8, 2];
echo longestSquareStreak($nums1) . "\n"; // Output: 3
$nums2 = [2, 3, 5, 6, 7];
echo longestSquareStreak($nums2) . "\n"; // Output: -1
?> Explanation:
Complexity Analysis
This solution efficiently finds the longest square streak or returns |
Beta Was this translation helpful? Give feedback.
We need to identify the longest square streak in the
nums
array. A square streak is a subsequence where each subsequent element is the square of the previous element, and it must be at least two elements long.Here's the solution approach:
Use a Set for Quick Lookup:
Iterate Through the Array:
Track Maximum Length: