Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 837 New 21 Game - Implementation

Sliding window optimization

Naive: for each dp[i]dp[i], sum last maxPtsmaxPts values. O(nmaxPts)O(n \cdot maxPts) total. improvement: maintain a running sum SS of the last maxPtsmaxPts probabilities. dp[i]=S/maxPtsdp[i] = S / maxPts. Update SS: add dp[i]dp[i] (if i<ki < k, since we keep drawing), subtract dp[imaxPts]dp[i - maxPts] (if valid). Final complexity: O(n)O(n) time, O(n)O(n) space. The sliding window avoids recomputing the sum. The sliding window sum avoids recomputing the last maxPts probabilities. This is a common DP improvement.

Time complexity: O(n)O(n).

Space complexity: O(n)O(n).