forked from antimatter007/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 2172.Maximum-AND-Sum-of-Array_v1.cpp
- Loading branch information
1 parent
37c3890
commit f8a7128
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
33 changes: 33 additions & 0 deletions
33
Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/2172.Maximum-AND-Sum-of-Array_v1.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
class Solution { | ||
public: | ||
int maximumANDSum(vector<int>& nums, int numSlots) | ||
{ | ||
int n = nums.size(); | ||
nums.insert(nums.begin(), 0); | ||
int m = pow(3, numSlots); | ||
vector<vector<int>>dp(n+1, vector<int>(m, INT_MIN/2)); | ||
dp[0][0] = 0; | ||
|
||
int ret = 0; | ||
for (int i=1; i<=n; i++) | ||
for (int state = 0; state < m; state++) | ||
{ | ||
for (int j=0; j<numSlots; j++) | ||
{ | ||
if (filled(state, j)>=1) | ||
dp[i][state] = max(dp[i][state], dp[i-1][state - pow(3,j)] + (nums[i]&(j+1))); | ||
} | ||
if (i==n) | ||
ret = max(ret, dp[i][state]); | ||
} | ||
|
||
return ret; | ||
} | ||
|
||
bool filled(int state, int k) | ||
{ | ||
for (int i=0; i<k; i++) | ||
state/=3; | ||
return state%3; | ||
} | ||
}; |