710022. Maximum Winning score

Medium

Maximum Winning score

Slug: maximum-winning-score--170637

Difficulty: Medium

Id: 710022

Topic Tags: Binary Search Tree, Data Structures

Company Tags: Morgan Stanley

Summary

In this problem, we are given a binary search tree where each node has an integer value. We need to find the maximum winning score that can be achieved by traversing the tree in a specific manner. The winning score is calculated as the sum of all nodes at a given depth minus the sum of all nodes at the next depth. We can solve this problem using dynamic programming, where we maintain a running total of the sums at each depth.

Detailed Explanation

To solve this problem, we first need to traverse the binary search tree in a depth-first manner. This is because the winning score calculation involves comparing values at different depths, which requires us to know the node values at each level before moving on to the next one.

We can use a recursive approach to perform the traversal. At each step, we calculate the sum of all nodes at the current depth and store it in a variable sumAtDepth. We then compare this sum with the sum of all nodes at the previous depth, which is stored in a variable prevSum.

If the current depth is 0 (i.e., we are at the root node), we initialize prevSum to 0. If the current depth is greater than 0, we update prevSum with the sum of all nodes at the previous depth.

We then calculate the winning score for the current depth as the difference between the current sum and the previous sum. We store this value in a variable winningScore.

Finally, we return the maximum winning score found during the traversal.

The time complexity of this algorithm is O(n), where n is the number of nodes in the binary search tree. The space complexity is O(h), where h is the height of the tree, since we need to store the sums at each depth level.

Optimized Solutions

Java

View on GeeksforGeeks
public int maxWinningScore(Node node) {
    if (node == null) return 0;

    int sumAtDepth = 0;
    int prevSum = 0;
    int winningScore = 0;

    for (int i = 0; i < node.depth; i++) {
        sumAtDepth += node.values[i];
        if (i > 0) {
            winningScore = Math.max(winningScore, sumAtDepth - prevSum);
            prevSum = sumAtDepth;
        }
    }

    return winningScore;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.