Medium
You are given an array of positive integers nums
.
You need to select a subset of nums
which satisfies the following condition:
[x, x2, x4, ..., xk/2, xk, xk/2, ..., x4, x2, x]
(Note that k
can be be any non-negative power of 2
). For example, [2, 4, 16, 4, 2]
and [3, 9, 3]
follow the pattern while [2, 4, 8, 4, 2]
does not.Return the maximum number of elements in a subset that satisfies these conditions.
Example 1:
Input: nums = [5,4,1,2,2]
Output: 3
Explanation: We can select the subset {4,2,2}, which can be placed in the array as [2,4,2] which follows the pattern and 22 == 4. Hence the answer is 3.
Example 2:
Input: nums = [1,3,2,4]
Output: 1
Explanation: We can select the subset {1}, which can be placed in the array as [1] which follows the pattern. Hence the answer is 1. Note that we could have also selected the subsets {2}, {3}, or {4}, there may be multiple subsets which provide the same answer.
Constraints:
2 <= nums.length <= 105
1 <= nums[i] <= 109
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int maximumLength(int[] nums) {
return withHashMap(nums);
}
private int withHashMap(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (int i : nums) {
map.put(i, map.getOrDefault(i, 0) + 1);
}
int ans = 0;
if (map.containsKey(1)) {
if (map.get(1) % 2 == 0) {
ans = map.get(1) - 1;
} else {
ans = map.get(1);
}
}
for (int key : map.keySet()) {
if (key == 1) {
continue;
}
int len = findSeries(map, key);
ans = Math.max(ans, len);
}
return ans;
}
private int findSeries(Map<Integer, Integer> map, int key) {
int sqr = key * key;
if (map.containsKey(sqr)) {
if (map.get(key) >= 2) {
return 2 + findSeries(map, sqr);
} else {
return 1;
}
} else {
return 1;
}
}
}