|
| 1 | +/* |
| 2 | + * MIT License |
| 3 | + * |
| 4 | + * Copyright (c) 2018 Christopher Friedt |
| 5 | + * |
| 6 | + * Permission is hereby granted, free of charge, to any person obtaining a copy |
| 7 | + * of this software and associated documentation files (the "Software"), to deal |
| 8 | + * in the Software without restriction, including without limitation the rights |
| 9 | + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 10 | + * copies of the Software, and to permit persons to whom the Software is |
| 11 | + * furnished to do so, subject to the following conditions: |
| 12 | + * |
| 13 | + * The above copyright notice and this permission notice shall be included in all |
| 14 | + * copies or substantial portions of the Software. |
| 15 | + * |
| 16 | + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 | + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 | + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 | + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 | + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 | + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 22 | + * SOFTWARE. |
| 23 | + */ |
| 24 | + |
| 25 | +#include <climits> |
| 26 | +#include <utility> |
| 27 | +#include <vector> |
| 28 | + |
| 29 | +using namespace std; |
| 30 | + |
| 31 | +class Solution { |
| 32 | +public: |
| 33 | + |
| 34 | + // https://leetcode.com/problems/predict-the-winner/ |
| 35 | + |
| 36 | + bool PredictTheWinner(vector<int>& nums) { |
| 37 | + // This is a DP problem because |
| 38 | + // 1) there are overlapping subproblems |
| 39 | + // 2) an optimal substructure |
| 40 | + |
| 41 | + // To illustrate, let's look at the [1,5,2] example |
| 42 | + // |
| 43 | + // (0,[1,5,2]) |
| 44 | + // max (bc it's player 1's turn) |
| 45 | + // (1,[5,2]) (-2,[1,5]) |
| 46 | + // min (bc it's player 2's turn) |
| 47 | + // (6,[2]) (-1,[5]) |
| 48 | + // max max |
| 49 | + // (8,[]) (4,[]) (4,[]) (-6,[]) |
| 50 | + |
| 51 | + const size_t N = nums.size(); |
| 52 | + vector<vector<int>> cache( N, vector<int>( N, INT_MIN ) ); |
| 53 | + |
| 54 | + return helper( nums, 0, N - 1, cache ) >= 0; |
| 55 | + } |
| 56 | + |
| 57 | +protected: |
| 58 | + static int helper( const vector<int> & nums, size_t l, size_t r, vector<vector<int>> & cache ) { |
| 59 | + if ( l == r ) { |
| 60 | + return 0; |
| 61 | + } |
| 62 | + if ( INT_MIN != cache[ l ][ r ] ) { |
| 63 | + return cache[ l ][ r ]; |
| 64 | + } |
| 65 | + int a = nums[ l ] - helper( nums, l + 1, r, cache ); |
| 66 | + int b = nums[ r ] - helper( nums, l, r - 1, cache ); |
| 67 | + cache[ l ][ r ] = max( a, b ); |
| 68 | + return cache[ l ][ r ]; |
| 69 | + } |
| 70 | +}; |
0 commit comments