You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法定位运行时错误根源:HackerRank Minion Game代码求助

Minion Game Code: Memory & Performance Issues Explained

Hey there! Let's break down why your code might be hitting errors (like timeouts or memory limits) on HackerRank's Minion Game problem.

The Core Problem with Your Current Code

Your approach stores every single valid substring in lists st and ke before counting their lengths. For a string of length n, this creates O(n²) substrings—way too many when n is large (like HackerRank's test cases that might use strings with thousands of characters).

For example, if the input string is 1000 characters long, your code would generate 500,500 substrings. That's a massive amount of memory usage, and the nested loops will take way too long to run, leading to timeouts or memory errors.

A Better Approach: Calculate Scores Directly

You don't need to store any substrings at all! Instead, calculate the score for each player on the fly:

  • Stuart's score: Sum the number of substrings starting with each consonant. For a character at index i, there are len(s) - i substrings starting at i (since you can take the substring from i to i, i to i+1, ..., i to the end of the string).
  • Kevin's score: Do the same for vowels (A, E, I, O, U).

Fixed Code

def minion_game(s):
    vowels = {'A', 'E', 'I', 'O', 'U'}
    stuart_score = 0
    kevin_score = 0
    n = len(s)
    for i in range(n):
        if s[i] in vowels:
            kevin_score += n - i
        else:
            stuart_score += n - i
    
    if stuart_score > kevin_score:
        print(f"Stuart {stuart_score}")
    elif kevin_score > stuart_score:
        print(f"Kevin {kevin_score}")
    else:
        print("Draw")

if __name__ == '__main__':
    s = input().strip()
    minion_game(s)

Why This Works

  • Memory Efficiency: We only use a few variables to track scores, no huge lists of substrings.
  • Time Efficiency: Runs in O(n) time (single loop through the string), which handles even the largest input sizes easily.

内容的提问来源于stack exchange,提问作者user350331

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:42:29