LeetCode 2173: Longest Winning Streak Solution

Master LeetCode problem 2173 (Longest Winning Streak), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2173. Longest Winning Streak

Problem Explanation

Explanation

To solve this problem, we can use dynamic programming. We will iterate through the array of game results and keep track of the longest winning streak ending at each position. We will maintain two arrays - one to store the longest winning streak ending at each position when the current game is a win, and another to store the longest winning streak ending at each position when the current game is a loss. We will update these arrays based on the current game result.

At each position, the longest winning streak ending at that position is determined by considering the longest winning streak ending at the previous position and updating it accordingly.

After processing all the games, the maximum value in the winning streak array will be the length of the longest winning streak.

  • Time complexity: O(n) where n is the number of games
  • Space complexity: O(n) for storing the arrays

Solution Code

class Solution {
    public int longestWinningStreak(int[] games) {
        int n = games.length;
        int[] winStreak = new int[n];
        int[] lossStreak = new int[n];

        winStreak[0] = games[0] == 1 ? 1 : 0;
        lossStreak[0] = games[0] == 0 ? 1 : 0;

        int maxStreak = Math.max(winStreak[0], lossStreak[0]);

        for (int i = 1; i < n; i++) {
            if (games[i] == 1) {
                winStreak[i] = winStreak[i - 1] + 1;
                lossStreak[i] = 0;
            } else {
                lossStreak[i] = lossStreak[i - 1] + 1;
                winStreak[i] = 0;
            }
            maxStreak = Math.max(maxStreak, Math.max(winStreak[i], lossStreak[i]));
        }

        return maxStreak;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2173 (Longest Winning Streak)?

This page provides optimized solutions for LeetCode problem 2173 (Longest Winning Streak) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2173 (Longest Winning Streak)?

The time complexity for LeetCode 2173 (Longest Winning Streak) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2173 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2173 in Java, C++, or Python.

Back to LeetCode Solutions