Skip to content

Instantly share code, notes, and snippets.

@walkingtospace
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walkingtospace/6a739eb80e6344591dcf to your computer and use it in GitHub Desktop.
Save walkingtospace/6a739eb80e6344591dcf to your computer and use it in GitHub Desktop.
findMaxScore
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