Last active
August 29, 2015 14:20
-
-
Save walkingtospace/6a739eb80e6344591dcf to your computer and use it in GitHub Desktop.
findMaxScore
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
struct Node | |
{ | |
int score; | |
Node* left; | |
Node* right; | |
}; | |
//M(r,k) returns the maximum sum of score of size k from root r. M(r,k) = max( M(l,i), M(r,j)); i+j = k and i,j>0 | |
int findMaxScore(Node* node, int k) { | |
vector<int> sum; | |
vector<int>::const_iterator it; | |
if (node == NULL) return -1; // wrong pruning | |
if (k == 1) return node->score; | |
for (int i = 1; i < k; ++i){ | |
int left = findMaxScore(node->left, i); | |
int right = findMaxScore(node->right, k - i); | |
if (left != -1 && right != -1) sum.push_back(left+right); | |
} | |
if (sum.size() > 0) return *(max_element(sum.begin(), sum.end())); //O(n); | |
else return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment