problems(rs): solve “486. Predict the Winner”
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
8275274674
commit
0d50e8082a
1 changed files with 22 additions and 0 deletions
22
problems/rs/predict-the-winner.rs
Normal file
22
problems/rs/predict-the-winner.rs
Normal file
|
@ -0,0 +1,22 @@
|
|||
use std::cmp::max;
|
||||
|
||||
impl Solution {
|
||||
pub fn predict_the_winner(nums: Vec<i32>) -> bool {
|
||||
let mut dp = vec![vec![0; nums.len()]; nums.len()];
|
||||
|
||||
// initialize
|
||||
for (i, &num) in nums.iter().enumerate() {
|
||||
dp[i][i] = num;
|
||||
}
|
||||
|
||||
// carry on the DP
|
||||
for d in 1..nums.len() {
|
||||
for l in 0..nums.len() - d {
|
||||
let r = l + d;
|
||||
dp[l][r] = max(nums[l] - dp[l + 1][r], nums[r] - dp[l][r - 1]);
|
||||
}
|
||||
}
|
||||
|
||||
dp[0][nums.len() - 1] >= 0
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue