Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8439e87

Browse files
Create 3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits.cpp
1 parent 8d79a12 commit 8439e87

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
class TrieNode {
2+
public:
3+
TrieNode* next[2];
4+
TrieNode()
5+
{
6+
for (int i=0; i<2; i++)
7+
next[i]=NULL;
8+
}
9+
};
10+
11+
class Solution {
12+
TrieNode* root;
13+
public:
14+
void add(int x) {
15+
TrieNode* node = root;
16+
for (int i=0; i<31; i++) {
17+
int b = ((x>>(30-i))&1);
18+
if (!node->next[b])
19+
node->next[b] = new TrieNode();
20+
node = node->next[b];
21+
}
22+
}
23+
24+
int dfs(TrieNode* node, int i, int x) {
25+
if (node==NULL) {
26+
return -1;
27+
}
28+
if (i==31) return 0;
29+
30+
int b = ((x>>(30-i))&1);
31+
32+
if (b==1) {
33+
int ans = dfs(node->next[0], i+1, x);
34+
if (ans!=-1) return ans;
35+
else return -1;
36+
}
37+
else {
38+
int ans1 = dfs(node->next[1], i+1, x);
39+
int ans2 = dfs(node->next[0], i+1, x);
40+
if (ans1!=-1)
41+
return (1<<(30-i))+ans1;
42+
if (ans2!=-1)
43+
return ans2;
44+
return -1;
45+
}
46+
}
47+
48+
long long maxProduct(vector<int>& nums) {
49+
root = new TrieNode();
50+
int n = nums.size();
51+
52+
long long ret = 0;
53+
for (int x: nums) {
54+
int ans = dfs(root, 0, x);
55+
if (ans!=-1) ret = max(ret, (long long)x*ans);
56+
add(x);
57+
}
58+
59+
return ret;
60+
}
61+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /