Datasets:

inputs
stringlengths
50
14k
targets
stringlengths
4
655k
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s. Return the longest happy prefix of s . Return an empty string if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". Example 2: Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string. Example 3: Input: s = "leetcodeleet" Output: "leet" Example 4: Input: s = "a" Output: ""   Constraints: 1 <= s.length <= 10^5 s contains only lowercase English letters.
class Solution: # kmp, time: O(n), space: O(n) # build the LPS table; lps: longest proper prefix which is also suffix. # lps[i]: for pattern[:i], the longest prefix which is a also the suffix def build(self, p): leng = 0 i = 1 lps = [0] while i < len(p): if p[i] == p[leng]: i += 1 leng += 1 lps.append(leng) else: if leng: leng = lps[leng - 1] else: lps.append(0) i += 1 return lps def longestPrefix2(self, s: str) -> str: lps = self.build(s) return s[:lps[-1]] # rolling hash # for the string of i size, the hash is: s[0] * 26 ^ (i - 1) + s[1] * 26 ^ (i -2) + ... + s[i - 2] * 26 + s[i - 1]. def longestPrefix(self, s: str) -> str: mul = 1; mod = pow(10, 9) + 7 i = 0; j = len(s) - 1 res = 0 hash1 = 0; hash2 = 0 while i < len(s) - 1 and j > 0: hash1 = (hash1 * 26 + ord(s[i]) - ord('a')) % mod # s[n-1] -> s[n-2]*26 + s[n-1] -> s[n-3]*26^2 + s[n-2]*26 + s[n-1] hash2 = (hash2 + mul * (ord(s[j]) - ord('a'))) % mod mul = mul * 26 % mod if hash1 == hash2: res = i + 1 i += 1 j -= 1 return s[:res]
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s. Return the longest happy prefix of s . Return an empty string if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". Example 2: Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string. Example 3: Input: s = "leetcodeleet" Output: "leet" Example 4: Input: s = "a" Output: ""   Constraints: 1 <= s.length <= 10^5 s contains only lowercase English letters.
class Solution: def longestPrefix(self, s: str) -> str: length = len(s) for i in range(1, length): if s[i] == s[0] and s[i:] == s[:length - i]: return s[i:] return ''
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s. Return the longest happy prefix of s . Return an empty string if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". Example 2: Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string. Example 3: Input: s = "leetcodeleet" Output: "leet" Example 4: Input: s = "a" Output: ""   Constraints: 1 <= s.length <= 10^5 s contains only lowercase English letters.
class Solution: def longestPrefix(self, s: str) -> str: p1 = s[0] length = len(s) for i in range(1, len(s)): if s[i] == p1: if s[i:] == s[:length - i]: return s[i:] return ''
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s. Return the longest happy prefix of s . Return an empty string if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". Example 2: Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string. Example 3: Input: s = "leetcodeleet" Output: "leet" Example 4: Input: s = "a" Output: ""   Constraints: 1 <= s.length <= 10^5 s contains only lowercase English letters.
class Solution: def longestPrefix(self, s: str) -> str: p1 = s[0] length = len(s) for i in range(1, len(s)): if s[i] == p1 and s[i:] == s[:length - i]: return s[i:] return ''
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s. Return the longest happy prefix of s . Return an empty string if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". Example 2: Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string. Example 3: Input: s = "leetcodeleet" Output: "leet" Example 4: Input: s = "a" Output: ""   Constraints: 1 <= s.length <= 10^5 s contains only lowercase English letters.
class Solution: def longestPrefix(self, s: str) -> str: for i in range(len(s)-1,-1,-1): if s[:i] == s[-i:]: return s[:i] return ''
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s. Return the longest happy prefix of s . Return an empty string if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". Example 2: Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string. Example 3: Input: s = "leetcodeleet" Output: "leet" Example 4: Input: s = "a" Output: ""   Constraints: 1 <= s.length <= 10^5 s contains only lowercase English letters.
''' Using Rabin-Karp incremental hash Reference: https://leetcode.com/problems/longest-happy-prefix/discuss/547446/C%2B%2BJava-with-picture-incremental-hash-and-KMP ''' class Solution: def longestPrefix(self, s: str) -> str: index = 0 MOD = 10**9 + 7 mul = 1 sLen = len(s) prefixHash, suffixHash = 0, 0 j = sLen-1 for i in range(sLen-1): first = ord(s[i]) - ord('a') last = ord(s[j]) - ord('a') prefixHash = (prefixHash*26 + first) % MOD suffixHash = (last*mul + suffixHash) % MOD mul = (mul*26) % MOD j-=1 if prefixHash == suffixHash: index = i+1 return s[:index]
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s. Return the longest happy prefix of s . Return an empty string if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". Example 2: Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string. Example 3: Input: s = "leetcodeleet" Output: "leet" Example 4: Input: s = "a" Output: ""   Constraints: 1 <= s.length <= 10^5 s contains only lowercase English letters.
#ababdababc #0012012340 class Solution: def computelps(self, p: str): m = len(p) lps = [0] * m i = 1 j = 0 while i < m: if p[i] != p[j]: if j == 0: i += 1 else: j = lps[j-1] else: j += 1 lps[i] = j i += 1 return lps def longestPrefix(self, s: str) -> str: lps = self.computelps(s) return s[:lps[-1]]
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s. Return the longest happy prefix of s . Return an empty string if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". Example 2: Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string. Example 3: Input: s = "leetcodeleet" Output: "leet" Example 4: Input: s = "a" Output: ""   Constraints: 1 <= s.length <= 10^5 s contains only lowercase English letters.
class Solution: def longestPrefix(self, s: str) -> str: n = len(s) k = n - 1 while k > 0: if s[:k] == s[-k:]: break k -= 1 return s[:k]
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s. Return the longest happy prefix of s . Return an empty string if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". Example 2: Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string. Example 3: Input: s = "leetcodeleet" Output: "leet" Example 4: Input: s = "a" Output: ""   Constraints: 1 <= s.length <= 10^5 s contains only lowercase English letters.
class Solution: def longestPrefix(self, st: str) -> str: a=st l=len(a) leng=0 i=1 lps=[0] while i<l: if a[leng]==a[i]: leng+=1 lps.append(leng) i+=1 else: if leng>0: leng=lps[leng-1] else: lps.append(0) i+=1 return st[:lps[-1]]
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s. Return the longest happy prefix of s . Return an empty string if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". Example 2: Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string. Example 3: Input: s = "leetcodeleet" Output: "leet" Example 4: Input: s = "a" Output: ""   Constraints: 1 <= s.length <= 10^5 s contains only lowercase English letters.
class Solution: def longestPrefix(self, s: str) -> str: sLen = len(s) if sLen == 1: return '' def happyNow(x): if s[:x] == s[-x:]: return True return False for length in range(sLen-1, 0, -1): if happyNow(length): return s[:length] return ''
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s. Return the longest happy prefix of s . Return an empty string if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". Example 2: Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string. Example 3: Input: s = "leetcodeleet" Output: "leet" Example 4: Input: s = "a" Output: ""   Constraints: 1 <= s.length <= 10^5 s contains only lowercase English letters.
class Solution: def longestPrefix(self, st: str) -> str: a = st l = len(a) i = 1 leng = 0 lps = [0] while i < l: if a[i] == a[leng]: leng += 1 lps.append(leng) i += 1 else: if leng > 0: leng = lps[leng - 1] else: lps.append(0) i += 1 return st[:lps[-1]]
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s. Return the longest happy prefix of s . Return an empty string if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". Example 2: Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string. Example 3: Input: s = "leetcodeleet" Output: "leet" Example 4: Input: s = "a" Output: ""   Constraints: 1 <= s.length <= 10^5 s contains only lowercase English letters.
class Solution: def longestPrefix(self, s: str) -> str: for i in range(len(s)-1,0,-1): # print(s[:i],s[len(s)-i:]) if s[:i]==s[len(s)-i:]: return s[:i] return ''
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s. Return the longest happy prefix of s . Return an empty string if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". Example 2: Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string. Example 3: Input: s = "leetcodeleet" Output: "leet" Example 4: Input: s = "a" Output: ""   Constraints: 1 <= s.length <= 10^5 s contains only lowercase English letters.
class Solution: def longestPrefix(self, s: str) -> str: res, l, r, mod = 0, 0, 0, 10**9 + 7 # now we start from the beginning and the end of the string # note you shouldn't search the whole string! because the longest prefix and suffix is the string itself for i in range(len(s) - 1): # based on an idea that is similar to prefix sum, we calculate the prefix hash in O(1) time. # specifically, we multiply the current prefix by 128 (which is the length of ASCII, but you can use another value as well) # then add in the ASCII value of the upcoming letter l = (l * 128 + ord(s[i])) % mod # similarly, we can calculate the suffix hash in O(1) time. # Specifically, we get the ith letter from the end using s[~i], note ~i is -i-1 # we find the pow(128, i, mod) and multiply by the letter's ASCII value # Actually, if we don't care about the beautifulness of the code, you can have a variable to keep track of pow(128, i, mod) as you increase i r = (r + pow(128, i, mod) * ord(s[~i])) % mod # we check if the prefix and suffix agrees, if yes, we find yet another longer prefix, so we record the index if l == r: res = i + 1 # after we finish searching the string, output the prefix return s[:res]
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s. Return the longest happy prefix of s . Return an empty string if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". Example 2: Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string. Example 3: Input: s = "leetcodeleet" Output: "leet" Example 4: Input: s = "a" Output: ""   Constraints: 1 <= s.length <= 10^5 s contains only lowercase English letters.
class Solution: def longestPrefix(self, s: str) -> str: res, l, r , mod = 0,0,0, 10**9+7 for i in range(len(s)-1): l = (l*128 + ord(s[i]))%mod r = (ord(s[~i])*(pow(128,i,mod)) + r)%mod if l==r: res = i+1 return s[:res ] def longestPrefix_bychance_Brute(self, s: str) -> str: res = '' for i in range(1, len(s)): if s[:i]==s[-i:]: res =s[:i] return res
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s. Return the longest happy prefix of s . Return an empty string if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". Example 2: Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string. Example 3: Input: s = "leetcodeleet" Output: "leet" Example 4: Input: s = "a" Output: ""   Constraints: 1 <= s.length <= 10^5 s contains only lowercase English letters.
class Solution: def longestPrefix(self, s: str) -> str: j, prefix, suffix = 0, 0, 0 mod = 10**9 + 9 for i in range(len(s)-1): prefix = (prefix * 128 + ord(s[i])) % mod suffix = (suffix + pow(128, i, mod) * ord(s[-i-1])) % mod if prefix == suffix: j = i + 1 return s[:j]
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
class Solution: def numPermsDISequence(self, S): dp = [1] * (len(S) + 1) for a, b in zip('I' + S, S): dp = list(itertools.accumulate(dp[:-1] if a == b else dp[-1:0:-1])) return dp[0] % (10**9 + 7)
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
class Solution: def numPermsDISequence(self, S: str) -> int: n = len(S) + 1 dp = [[0] * (n + 1) for _ in range(n+1)] dp[1][0] = 1 MOD = 10**9 + 7 for i in range(2,n+1): p = [0] + list(itertools.accumulate(dp[i-1])) for j in range(i): L,R = None,None if S[i-2] == 'D': #decreasing L = j R = i - 2 else: #increasing L = 0 R = j - 1 dp[i][j] = (p[R+1] - p[L])% MOD dp[i][j] %= MOD return sum(dp[n]) % MOD
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
class Solution: def numPermsDISequence(self, S: str) -> int: n = len(S) + 1 dp = [[0] * (n + 1) for _ in range(n+1)] dp[1][0] = 1 MOD = 10**9 + 7 for i in range(2,n+1): p = [0] + list(itertools.accumulate(dp[i-1])) for j in range(i): L,R = None,None if S[i-2] == 'D': #decreasing L = j R = i - 2 else: #increasing L = 0 R = j - 1 dp[i][j] = (p[R+1] - p[L])% MOD dp[i][j] %= MOD res = 0 for i in dp[n]: res += i res %= MOD return res
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
from functools import lru_cache class Solution: def numPermsDISequence(self, S): MOD = 10**9 + 7 N = len(S) @lru_cache(None) def dp(i, j): # How many ways to place P_i with relative rank j? if not (0 <= j <= i): return 0 if i == 0: return 1 elif S[i-1] == 'D': return (dp(i - 1, j) + dp(i, j + 1)) % MOD else: return (dp(i-1, j - 1) + dp(i, j - 1)) % MOD return sum(dp(N, j) for j in range(N+1)) % MOD
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
class Solution: def numPermsDISequence(self, S): MOD = 10**9 + 7 N = len(S) @lru_cache(None) def dp(i, j): # How many ways to place P_i with relative rank j? if not(0 <= j <= i): return 0 if i == 0: return 1 elif S[i-1] == 'D': return (dp(i, j+1) + dp(i-1, j)) % MOD else: return (dp(i, j-1) + dp(i-1, j-1)) % MOD return sum(dp(N, j) for j in range(N+1)) % MOD
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
class Solution: def numPermsDISequence(self, S: str) -> int: from functools import lru_cache MOD = 10**9 + 7 N = len(S) @lru_cache(None) def search(i, j): if not 0 <= j <= i: return 0 if i == 0: return 1 if S[i-1] == 'D': return (search(i, j+1) + search(i-1, j)) % MOD else: return (search(i, j-1) + search(i-1, j-1)) % MOD return sum(search(N, j) for j in range(len(S)+1)) % MOD
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
from functools import lru_cache class Solution: def numPermsDISequence(self, S): MOD = 10**9 + 7 N = len(S) @lru_cache(None) def dp(i, j): # How many ways to place P_i with relative rank j? if not(0 <= j <= i): return 0 if i == 0: return 1 elif S[i-1] == 'D': return (dp(i, j+1) + dp(i-1, j)) % MOD else: return (dp(i, j-1) + dp(i-1, j-1)) % MOD return sum(dp(N, j) for j in range(N+1)) % MOD
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
class Solution: def numPermsDISequence(self, S: str) -> int: MOD = 10**9 + 7 N = len(S) dp = [[0]*(N+1) for _ in range(N+1)] def solve(i, j): if not ( 0 <= j <= i): return 0 if dp[i][j]: return dp[i][j] if i == 0: return 1 if S[i-1] == 'D': dp[i][j] = (solve(i, j-1) + solve(i-1, j-1)) % MOD else: dp[i][j] = (solve(i, j+1) + solve(i-1, j)) % MOD return dp[i][j] return sum(solve(N, j) for j in range(N+1)) % MOD
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
from functools import lru_cache class Solution: def numPermsDISequence(self, S: str) -> int: MOD = 10 ** 9 + 7 @lru_cache(None) def presum(n, last): if last == 0: return 0 return DP(n, last - 1) + presum(n, last - 1) @lru_cache(None) def DP(n, last): if n == 0: return 1 if S[n - 1] == 'D': return (presum(n - 1, n) - presum(n - 1, last)) % MOD else: return presum(n - 1, last) % MOD return sum( DP(len(S), i) for i in range(len(S) + 1) ) % MOD
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
from functools import lru_cache class Solution: def numPermsDISequence(self, S: str) -> int: MOD = 10 ** 9 + 7 @lru_cache(None) def presum(n, last): if last == 0: return 0 return DP(n, last - 1) + presum(n, last - 1) @lru_cache(None) def DP(n, last): if n == 0: return 1 if S[n - 1] == 'D': return (presum(n - 1, n) - presum(n - 1, last)) % MOD else: return presum(n - 1, last) % MOD return presum(len(S), len(S) + 1) % MOD
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
class Solution: def numPermsDISequence(self, S: str) -> int: dp = [1] * (len(S)+1) for a , b in zip('I'+S, S): dp = list(itertools.accumulate(dp[:-1] if a == b else dp[-1:0:-1])) return dp[0] % (10**9+7)
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
from functools import lru_cache class Solution: def numPermsDISequence(self, S): MOD = 10**9 + 7 N = len(S) @lru_cache(None) def dp(i, j): # How many ways to place P_i with relative rank j? if not(0 <= j <= i): return 0 if i == 0: return 1 elif S[i-1] == 'D': return (dp(i, j+1) + dp(i-1, j)) % MOD else: return (dp(i, j-1) + dp(i-1, j-1)) % MOD return sum(dp(N, j) for j in range(N+1)) % MOD
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
from functools import lru_cache class Solution: def numPermsDISequence(self, S: str) -> int: MOD = 10**9 + 7 N = len(S) @lru_cache(None) def dp(i, j): # How many ways to place P_i with relative rank j? if not(0 <= j <= i): return 0 if i == 0: return 1 elif S[i-1] == 'D': return (dp(i, j+1) + dp(i-1, j)) % MOD else: return (dp(i, j-1) + dp(i-1, j-1)) % MOD return sum(dp(N, j) for j in range(N+1)) % MOD
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
class Solution: def numPermsDISequence(self, S: str) -> int: MOD = 10**9+7 n = len(S) @lru_cache(None) def dp(i, j): if not (0 <= j <= i): return 0 if i == 0: return 1 elif S[i-1] == 'D': return (dp(i, j+1)+ dp(i-1, j)) % MOD else: return (dp(i, j-1)+dp(i-1, j-1)) % MOD return sum(dp(n, j) for j in range(n+1)) % MOD
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
class Solution: def numPermsDISequence(self, S: str) -> int: n = len(S) MOD = 10 ** 9 + 7 dp = [[0]*(n+1) for _ in range(n+1)] dp[0][0] = 1 for i in range(1, n+1): for j in range(i+1): if S[i-1] == 'D': dp[i][j] = sum(dp[i-1][j:i] + [0]) % MOD else: dp[i][j] = sum(dp[i-1][:j] + [0]) % MOD return sum(dp[-1]) % MOD
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
class Solution: def numPermsDISequence(self, S: str) -> int: d = [0] * (len(S) + 1) d[0] = 1 for i,c in enumerate(S): if c == 'D': for j in range(i-1,-1,-1): d[j] += d[j+1] else: for j in range(1,i+1): d[j] += d[j-1] for j in range(i+1,0,-1): d[j] = d[j-1] d[0] = 0 return sum(d) % 1000000007
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
class Solution: def numPermsDISequence(self, S: str) -> int: M = pow(10, 9) + 7 N = len(S) S = '#' + S dp = [[0] * (N + 1) for _ in range(N + 1)] dp[0][0] = 1 for i in range(1, N + 1): for j in range(i + 1): if S[i] == 'D': for k in range(j, i + 1): dp[i][j] += dp[i-1][k] else: # S[i] == 'I' for k in range(0, j): dp[i][j] += dp[i-1][k] res = 0 for i in range(N + 1): res += dp[N][i] return res % M
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
class Solution: def numPermsDISequence(self, S: str) -> int: MOD = 10**9+7 N = len(S) @lru_cache(None) def dp(i,j): if i==0: return 1 elif S[i-1] == 'D': return sum(dp(i-1, k) for k in range(j,i)) % MOD else: return sum(dp(i-1,k) for k in range(j)) % MOD return sum(dp(N,j) for j in range(N+1)) % MOD
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
class Solution: def numPermsDISequence(self, s: str) -> int: n=len(s) dp=[[0 for i in range(n+1)] for i in range(n+1)] dp[0][0]=1 for i in range(1,n+1): for j in range(i+1): if(s[i-1]=='D'): for k in range(j,i): dp[i][j]+=dp[i-1][k] else: for k in range(j): dp[i][j]+=dp[i-1][k] # print(dp) return sum(dp[n][:])%(pow(10,9)+7)
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
class Solution: def numPermsDISequence(self, S: str) -> int: n = len(S) if n <= 1: return 1 dp = [[0 for _ in range(n+1)] for _ in range(n+1)] dp[0][0] = 1 for idx, s in enumerate(S): for end in range(idx+2): if s == 'D': for i in range(end, idx+2): dp[idx+1][end] += dp[idx][i] else: for i in range(end): dp[idx+1][end] += dp[idx][i] # for d in dp: print(d) return sum(dp[-1]) % (10 ** 9 + 7)
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
from functools import lru_cache class Solution: def numPermsDISequence(self, S): MOD = 10**9 + 7 N = len(S) @lru_cache(None) def dp(i, j): # How many ways to place P_i with relative rank j? if i == 0: return 1 elif S[i-1] == 'D': return sum(dp(i-1, k) for k in range(j, i)) % MOD else: return sum(dp(i-1, k) for k in range(j)) % MOD return sum(dp(N, j) for j in range(N+1)) % MOD
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
from functools import lru_cache class Solution: def numPermsDISequence(self, S: str) -> int: # Dynamic Programming # Time complexity: O(N^3) # Space complexity: O(N^2) MOD = 10**9 + 7 N = len(S) @lru_cache(None) def dp(i, j): # How many ways to place P_i with relative rank j? if i == 0: return 1 elif S[i - 1] == 'D': return sum(dp(i - 1, k) for k in range(j, i)) % MOD else: return sum(dp(i - 1, k) for k in range(j)) return sum(dp(N, j) for j in range(N + 1)) % MOD
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
from functools import lru_cache class Solution: def numPermsDISequence(self, S: str) -> int: ''' 这道题目的关键是第一步看到10**9+7知道用dp方法来做 dp[i]表示范围[0,i]的序列个数,然后发现不好找递推关系 这个时候肯定是隐藏的信息没用,外面需要通过实际的例子来总结影响个数的另外一个参数 序列是升还是降跟什么关系最大,那就是最后一个数字。DID模式,我们可以是1032,那么我们再加个D,要求递减 这个时候多出了一个4来,我们如何改造1032呢,直接加4是不行的,那么加一样的2?改成10432,相当于3,2都+1 加1呢?改成20431,相当于1,3,2都+1,那么规律是什么。 如果是D,那么只能放<=最后一个数的数,然后把原来所有>=尾巴的数都+1,最后一个数很重要 反过来想,如果是I,那么只能放>最后一个数的数,然后原来所有的>=新加的数都+1 ''' mod = 10 ** 9 + 7 n = len(S) @lru_cache(None) def dfs(i, j): # 位置i处数字j结尾 数字j的范围是0-i if i == 0: return 1 elif S[i - 1] == 'D': return sum(dfs(i - 1, k) for k in range(j, i)) % mod else: return sum(dfs(i - 1, k) for k in range(j)) % mod return sum(dfs(n, j) for j in range(n + 1)) % mod
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
from functools import lru_cache class Solution: def numPermsDISequence(self, S: str) -> int: MOD = 10**9+7 N = len(S) @lru_cache(None) def dp(i, j): if i==0: return 1 elif S[i-1] == 'D': return sum(dp(i-1,k) for k in range(j,i))%MOD else: return sum(dp(i-1,k) for k in range(j))%MOD return sum(dp(N, j) for j in range(N+1))%MOD
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
from functools import lru_cache class Solution: def numPermsDISequence(self, S: str) -> int: MOD = 10 ** 9 + 7 @lru_cache(None) def DP(n, last): if n == 0: return 1 if S[n - 1] == 'D': return sum( DP(n - 1, x - 1) for x in range(last + 1, n + 1) ) % MOD else: return sum( DP(n - 1, x) for x in range(last) ) % MOD return sum( DP(len(S), i) for i in range(len(S) + 1) ) % MOD
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
from functools import lru_cache class Solution: def numPermsDISequence(self, S: str) -> int: mod = 10**9+7 N = len(S) @lru_cache(None) def dp(i,j): print((i,j)) if i==0: return 1 elif S[i-1]=='D': return sum(dp(i-1,k) for k in range(j,i))%mod else: return sum(dp(i-1,k) for k in range(j))%mod return sum(dp(N,j) for j in range(N+1))%mod
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
class Solution: def numPermsDISequence(self, S: str) -> int: n = len(S) mod = 10**9 + 7 # solns[above][below] # if decreasing: # answer = sum solns[above+k][below-k-1] # if increasing: # answer = sum solns[above-k-1][below+k] solns = [[0] * (n+2) for _ in range(n+2)] solns[0][0] = 1 for i in range(1, n+1): for j in range(i+1): k = i - j if S[-i] == 'D': for r in range(0, k): solns[j][k] += solns[j+r][k-r-1] else: for r in range(0, j): solns[j][k] += solns[j-r-1][k+r] solns[j][k] %= mod result = sum(solns[i][n-i] for i in range(n+1)) return result % mod
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
from functools import lru_cache class Solution: def numPermsDISequence(self, S: str) -> int: MOD = 10 ** 9 + 7 def presum(n, last): return sum( DP(n, x) for x in range(last) ) @lru_cache(None) def DP(n, last): if n == 0: return 1 if S[n - 1] == 'D': return (presum(n - 1, n) - presum(n - 1, last)) % MOD else: return presum(n - 1, last) % MOD return sum( DP(len(S), i) for i in range(len(S) + 1) ) % MOD
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".) A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i: If S[i] == 'D', then P[i] > P[i+1], and; If S[i] == 'I', then P[i] < P[i+1]. How many valid permutations are there?  Since the answer may be large, return your answer modulo 10^9 + 7.   Example 1: Input: "DID" Output: 5 Explanation: The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0)   Note: 1 <= S.length <= 200 S consists only of characters from the set {'D', 'I'}.
class Solution: def numPermsDISequence(self, S: str) -> int: MOD = 10**9 + 7 N = len(S) dp = [[0]*(N+1) for _ in range(N+1)] def solve(i, j): if dp[i][j]: return dp[i][j] if i == 0: return 1 if S[i-1] == 'D': dp[i][j] = sum(solve(i-1, k) for k in range(j)) % MOD else: dp[i][j] = sum(solve(i-1, k) for k in range(j, i)) % MOD return dp[i][j] return sum(solve(N, j) for j in range(N+1)) % MOD
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: a,b,n=[slices[0]],[0],len(slices) for i in range(1,n): a.append(max(a[-1],slices[i])) b.append(max(b[-1],slices[i])) for i in range(2,2*n//3,2): aa,bb=[0]*(n-1),[0]*n for j in range(i,n-1): aa[j]=max(aa[j-1],a[j-2]+slices[j]) for j in range(i+1,n): bb[j]=max(bb[j-1],b[j-2]+slices[j]) a,b=aa,bb return max(a[-1],b[-1])
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: n = len(slices) rounds = n//3 def num_s(slices): # print(slices) n = len(slices) dp = [i for i in slices] for i in range(rounds): maxx = 0 dp2 = [0]*(i*2) for j in range(i*2,n): # print(j) if i == 0: dp2.append(max(maxx,slices[j])) maxx = dp2[j] else: dp2.append(max(maxx,slices[j] + dp[j-2])) maxx = dp2[j] dp = dp2 # print(dp, slices) return dp[len(dp)-1] return max(num_s(slices[1:]),num_s(slices[:n-1]))
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: @lru_cache(None) def dp(i, k): if k == 0 or i > j: return 0 return max(dp(i + 1, j, k), slices[i] + dp(i + 2, j, k - 1)) n = len(slices) k = n // 3 dp = collections.deque([[0] * (k + 1) for i in range(2)]) for i in range(n - 2, -1, -1): new_dp = [0] * (k + 1) for j in range(1, k + 1): new_dp[j] = max(dp[0][j], slices[i] + dp[1][j - 1]) dp.pop() dp.appendleft(new_dp) a = dp[0][k] dp.clear() dp.extend([[0] * (k + 1) for i in range(2)]) for i in range(n - 1, 0, -1): new_dp = [0] * (k + 1) for j in range(1, k + 1): new_dp[j] = max(dp[0][j], slices[i] + dp[1][j - 1]) dp.pop() dp.appendleft(new_dp) b = dp[0][k] return max(a, b)
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
from functools import lru_cache class Solution: def maxSizeSlices(self, w: List[int]) -> int: n = len(w) k = n // 3 results = [0, 0] for offset in range(2): cur = [0] * n prev = [0] * n for i in range(1, k + 1): cur[1] = w[offset] for j in range(2, n): cur[j] = max(prev[j - 2] + w[j - 1 + offset], cur[j - 1]) prev = cur cur = [0] * n results[offset] = prev[-1] return max(results)
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: n = len(slices) k = n // 3 dp1 = collections.deque([[0] * (k + 1) for i in range(2)]) dp2 = collections.deque([[0] * (k + 1) for i in range(2)]) for i in range(n - 2, -1, -1): new_dp1 = [0] * (k + 1) new_dp2 = [0] * (k + 1) for j in range(1, k + 1): new_dp1[j] = max(dp1[0][j], slices[i] + dp1[1][j - 1]) new_dp2[j] = max(dp2[0][j], slices[i + 1] + dp2[1][j - 1]) dp1.pop() dp1.appendleft(new_dp1) dp2.pop() dp2.appendleft(new_dp2) return max(dp1[0][k], dp2[0][k])
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: n = len(slices) // 3 def linear(arr): # index = nb slices eaten. a = [0] * (n+1) # Two slices ago. b = [0] * (n+1) # Previous slice. for x in arr: a, b = b, [i and max(x + a[i-1], b[i]) for i in range(n+1)] # print(a,b) return b[-1] return max(linear(slices[1:]), linear(slices[:-1]))
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
from functools import lru_cache class Solution: def maxSizeSlices(self, w: List[int]) -> int: n = len(w) k = n // 3 results = [0, 0] for offset in range(2): cur = [0] * n prev = [0] * n for i in range(1, k + 1): cur[1] = w[offset] for j in range(2, n): cur[j] = max(prev[j - 2] + w[j - 1 + offset], cur[j - 1]) prev[:] = cur cur[:] = [0] * n results[offset] = prev[-1] return max(results)
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: n = len(slices) // 3 def max_adj_sum(a): l = len(a) if l == 0: return 0 if l == 1: return a[0] dp = [[0] * l for i in range(n + 1)] for i in range(1, n + 1): dp[i][0] = a[0] for j in range(1, l): t = dp[i - 1][j - 2] if j >= 2 else 0 dp[i][j] = max(dp[i][j - 1], a[j] + t) #print(dp) return dp[n][-1] #print(max_adj_sum(slices[1:])) return max(max_adj_sum(slices[1:]), max_adj_sum(slices[:-1]))
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: ## hard m = len(slices) n = m // 3 dp = [[0]*(n+1) for i in range(m+1)] for i in range(m-2, -1, -1): for j in range(1, n+1): dp[i][j] = max(dp[i+1][j], slices[i]+dp[i+2][j-1]) #print(dp[0][n]) dp2 = [[0]*(n+1) for i in range(m+2)] for i in range(m-1, 0, -1): for j in range(1, n+1): dp2[i][j] = max(dp2[i+1][j], slices[i]+dp2[i+2][j-1]) return max(dp[0][n], dp2[1][n])
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, w: List[int]) -> int: k = len(w)//3 #last element is excluded dp1 = [[0]*(len(w)) for _ in range(k+1)] #first element is excluded dp2 = [[0]*(len(w)) for _ in range(k+1)] for n in range(1,k+1): for i in range(1,len(w)): if i==1: dp1[n][i] = w[i-1] dp2[n][i] = w[i] continue dp1[n][i] = max(dp1[n-1][i-2]+w[i-1],dp1[n][i-1]) dp2[n][i] = max(dp2[n-1][i-2]+w[i],dp2[n][i-1]) return max(dp1[-1][-1],dp2[-1][-1])
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: n=len(slices) idx = min(range(n), key=lambda x: slices[x]) slices = slices[idx+1:] + slices[:idx] @lru_cache(None) def dp(i,k): if i>=n-1 or k==0: return 0 return max(slices[i]+dp(i+2,k-1),dp(i+1,k)) return dp(0,n//3)
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: m = len(slices) n = m // 3 slice1 = slices[:m - 1] slice2 = slices[1:] return max(self.max_sum(slice1, n), self.max_sum(slice2, n)) def max_sum(self, slices, n): m = len(slices) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if i == 1: dp[i][j] = slices[0] else: dp[i][j] = max(dp[i - 1][j], dp[i - 2][j - 1] + slices[i - 1]) return dp[m][n]
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, w: List[int]) -> int: k = len(w)//3 #last element is excluded dp1 = [[0]*(len(w)) for _ in range(k+1)] #first element is excluded dp2 = [[0]*(len(w)) for _ in range(k+1)] for n in range(1,k+1): for i in range(1,len(w)): if i==1: dp1[n][i]=w[0] dp2[n][i]=w[1] continue dp1[n][i] = max(dp1[n-1][i-2]+w[i-1],dp1[n][i-1]) dp2[n][i] = max(dp2[n-1][i-2]+w[i],dp2[n][i-1]) return max(dp1[k][-1],dp2[k][-1])
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
from functools import lru_cache class Solution: def maxSizeSlices(self, w: List[int]) -> int: n = len(w) k = n // 3 dp1 = [[0] * n for _ in range(k + 1)] for i in range(1, k + 1): dp1[i][1] = w[0] for j in range(2, n): dp1[i][j] = max(dp1[i - 1][j - 2] + w[j - 1], dp1[i][j - 1]) r1 = dp1[-1][-1] for i in range(1, k + 1): dp1[i][1] = w[1] for j in range(2, n): dp1[i][j] = max(dp1[i - 1][j - 2] + w[j], dp1[i][j - 1]) return max(dp1[-1][-1], r1)
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: self.slices = slices n = len(self.slices) self.mem = dict() rv1 = self.dfs(1, n-1, n//3) rv2 = self.dfs(0, n-2, n//3) return max(rv1, rv2) def dfs(self, i, j, k): if k <= 0: return 0 if j - i + 1 < 2*k-1: return -float('inf') key = (i,j,k) if key in self.mem: return self.mem[key] rv = max(self.dfs(i+1, j, k), self.slices[i] + self.dfs(i+2, j, k-1)) self.mem[key] = rv return rv
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def __init__(self): self.dp = {} def solve_linear(self, slices, ind, to_choose): if (ind, to_choose) not in self.dp: N = len(slices) if N <= ind or to_choose == 0: return 0 result_choose = self.solve_linear(slices, ind + 2, to_choose - 1) result_not_choose = self.solve_linear(slices, ind + 1, to_choose) self.dp[(ind, to_choose)] = max(result_choose + slices[ind], result_not_choose) return self.dp[(ind, to_choose)] def maxSizeSlices(self, slices: List[int]) -> int: min_elem = min(slices) min_ind = 0 while slices[min_ind] != min_elem: min_ind += 1 N = len(slices) min_ind += 1 arr = [0 for _ in range(N)] for i in range(N): arr[i] = slices[(min_ind + i) % N] return self.solve_linear(arr, 0, int(N/3))
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: def helper(start, end): dp = [[0] * n for _ in range(end-start+1)] dp[0] = [slices[start]] * n dp[1] = [max(slices[start], slices[start+1])] * n for i in range(start+2, end+1): dp[i-start][0] = max(slices[i], dp[i-start-1][0]) for j in range(1, n): dp[i-start][j] = max(dp[i-start-1][j], slices[i] + dp[i-start-2][j-1]) return dp[-1][-1] n = len(slices) // 3 return max(helper(0, len(slices) - 2), helper(1, len(slices) - 1))
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: k = len(slices) // 3 dp1 = [[0] * len(slices) for _ in range(k + 1)] dp2 = [[0] * len(slices) for _ in range(k + 1)] for i in range(1, k + 1): for j in range(1, len(slices)): if j == 1: dp1[i][j] = slices[j - 1] dp2[i][j] = slices[j] else: dp1[i][j] = max(dp1[i - 1][j - 2] + slices[j - 1], dp1[i][j - 1]) dp2[i][j] = max(dp2[i - 1][j - 2] + slices[j], dp2[i][j - 1]) return max(dp1[-1][-1], dp2[-1][-1])
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
# class LinkedNode: # def __init__(self, val): # self.val = val # self.next = None # self.prev = None class Solution: def maxSizeSlices(self, slices: List[int]) -> int: slicesN = len(slices) target = slicesN//3 table1 = [[0 for i in range(slicesN)] for ti in range(target+1)] table2 = [[0 for i in range(slicesN)] for ti in range(target+1)] for ti in range(1, target + 1): for i in range(1, slicesN): if i == 1: table1[ti][i] = slices[i] table2[ti][i] = slices[i-1] continue table1[ti][i] = max(table1[ti][i-1], table1[ti-1][i-2] + slices[i]) table2[ti][i] = max(table2[ti][i-1], table2[ti-1][i-2] + slices[i-1]) return max(table1[-1][-1], table2[-1][-1]) # slicesN = len(slices) # table = [[] for _ in range(slicesN)] # target = slicesN//3 # table[-1] = [slices[-1]] # table[-2] = [slices[-2]] # table[-3] = [slices[-3], slices[-3]+slices[-1]] # table2 = [[] for _ in range(slicesN)] # table2[-1] = [slices[-1]] # table2[-2] = [slices[-2]] # table2[-3] = [slices[-3]] # for i in range(slicesN-4, -1, -1): # table[i].append(slices[i]) # table2[i].append(slices[i]) # for j in range(i+2, slicesN): # for k, sumTemp in enumerate(table[j]): # if k+1 > target: # break # if k+1 >= len(table[i]): # table[i].append(sumTemp + slices[i]) # else: # table[i][k+1] = max(table[i][k+1], sumTemp + slices[i]) # for k, sumTemp in enumerate(table2[j]): # if k+1 > target: # break # if k+1 >= len(table2[i]): # table2[i].append(sumTemp + slices[i]) # else: # table2[i][k+1] = max(table2[i][k+1], sumTemp + slices[i]) # target = slicesN//3 # ans1 = 0 # for i, sums in enumerate(table[1:]): # if len(sums) >= target: # ans1 = max(ans1, sums[target-1]) # ans2 = 0 # for i, sums in enumerate(table2): # if len(sums) >= target: # ans2 = max(ans2, sums[target-1]) # return max(ans1, ans2) # @lru_cache # def takePizza(slices0): # # print(slices0) # n = len(slices0) # if n == 3: # return max(slices0) # subAns = max(slices0[0] + takePizza(slices0[2:n-1]), slices0[n-1] + takePizza(slices0[1:n-2])) # for i in range(1, n-1): # subAns = max(subAns, slices0[i] + takePizza(slices0[:i-1] + slices0[i+2:])) # return subAns # return takePizza(tuple(slices)) # pointerDict = {} # head = LinkedNode(0) # preNode = head # for i, pizzaSlice in enumerate(slices): # newLN = LinkedNode(pizzaSlice) # pointerDict[newLN] = i # preNode.next = newLN # newLN.prev = preNode # preNode = newLN # preNode.next = head # head.prev = preNode # slicesN = len(slices) # fullMask = (1 << slicesN -1) # dp = {} # def takePizza(m0, leftOver): # if m0 in dp: # return dp[m0] # subAns = 0 # if leftOver == 3: # subAns = 0 # pointer = head.next # while pointer != head: # subAns = max(subAns, pointer.val) # # print(pointer.val, pointerDict[pointer]) # pointer = pointer.next # # print(subAns) # dp[m0] = subAns # return subAns # pointer = head.next # while pointer != head: # m1 = m0|(1<<pointerDict[pointer]) # if pointer.next == head: # endPointer = head.next # m1 |= (1<<pointerDict[head.next]) # else: # endPointer = pointer.next # m1 |= (1<<pointerDict[pointer.next]) # if pointer.prev == head: # startPointer = head.prev # m1 |= (1<<pointerDict[head.prev]) # else: # startPointer = pointer.prev # m1 |= (1<<pointerDict[pointer.prev]) # if pointer.next == head or pointer.prev == head: # headPrev = head.prev # headNext = head.next # head.next = endPointer.next # head.prev = startPointer.prev # head.prev.next = head # head.next.prev = head # subAns = max(subAns, pointer.val + takePizza(m1, leftOver-3)) # head.prev = headPrev # head.next = headNext # else: # startPointer.prev.next = endPointer.next # endPointer.next.prev = startPointer.prev # subAns = max(subAns, pointer.val + takePizza(m1, leftOver-3)) # startPointer.prev.next = startPointer # startPointer.next.pre = startPointer # pointer.prev.next = pointer # pointer.next.prev = pointer # endPointer.prev.next = endPointer # endPointer.next.pre = endPointer # pointer = pointer.next # dp[m0] = subAns # return subAns # return takePizza(0, slicesN)
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: n = len(slices) nPick = n//3 total = [[[0] * (n + 1) for _ in range(nPick+1)] for __ in range(2)] total[1][1][1] = slices[0] for i in range(1, nPick+1): for j in range(2, n + 1): total[0][i][j] = max(slices[j-1] + total[0][i-1][j-2], total[0][i][j-1]) total[1][i][j] = max(slices[j-1] + total[1][i-1][j-2], total[1][i][j-1]) return max(max(total[0][nPick]), max(total[1][nPick][:-1]))
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, w: List[int]) -> int: n_picks = len(w)//3 dp1 = [[0 for _ in range(len(w))] for _ in range(n_picks+1)] dp2 = [[0 for _ in range(len(w))] for _ in range(n_picks+1)] for i in range(1,n_picks+1): for j in range(1,len(w)): if j == 1: dp1[i][j] = w[j-1] dp2[i][j] = w[j] continue dp1[i][j] = max(w[j-1] + dp1[i-1][j-2],dp1[i][j-1]) dp2[i][j] = max(w[j] + dp2[i-1][j-2],dp2[i][j-1]) return max(dp1[n_picks][len(w)-1],dp2[n_picks][len(w)-1])
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: def find(arr,n): dp1=[0 for i in range(n+1)] dp2=[0 for i in range(n+1)] dp2[1]=arr[0] for i in range(1,len(arr)): new_dp1=[max(dp1[j],dp2[j]) for j in range(n+1)] new_dp2=[0]+[arr[i]+dp1[j-1] for j in range(1,n+1)] dp1=new_dp1 dp2=new_dp2 return max(dp2[-1],dp1[-1]) n=len(slices)//3 return max(find(slices[:-1],n),find(slices[1:],n))
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, s: List[int]) -> int: ct = len(s)//3 @lru_cache(None) def f(l, r, n): if n == 0: return 0 if l > r: return -1e18 if n == 1: return max(s[l:r+1]) return max(f(l+1, r, n), s[l] + f(l+2, r, n-1)) return max(f(1, len(s)-1, ct), s[0] + f(2, len(s)-2, ct-1))
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def dp(self, i, j, k, l): # max by taking k from s[i:j] assume cycle if l = 1 else no-cycle if (i, j, k, l) not in self.memo: if k == 1: self.memo[(i, j, k, l)] = max(self.s[i:j]) elif j - i < 2 * k - 1: self.memo[(i, j, k, l)] = float('-inf') else: # max of taking self.s[i] and not taking self.s[i] at this step self.memo[(i, j, k, l)] = max(self.dp(i + 2, j - l, k - 1, 0) + self.s[i], self.dp(i + 1, j, k, 0)) return self.memo[(i, j, k, l)] def maxSizeSlices(self, slices: List[int]) -> int: # Q0213, dynamic programming self.memo, self.s, n = {}, slices, len(slices) return self.dp(0, n, n // 3, 1)
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
from functools import lru_cache class Solution: def maxSizeSlices(self, w: List[int]) -> int: n = len(w) k = n // 3 dp1 = [[0] * n for _ in range(k + 1)] results = [0, 0] for offset in range(2): for i in range(1, k + 1): dp1[i][1] = w[offset] for j in range(2, n): dp1[i][j] = max(dp1[i - 1][j - 2] + w[j - 1 + offset], dp1[i][j - 1]) results[offset] = dp1[-1][-1] return max(results)
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: l=len(slices) s1=slices[0:l-1] s2=slices[1:l] n=l//3 def summax(arr): dp=[[0]*(n+1) for i in range(l+1)] p=len(arr) for i in range(1,p+1): for j in range(1,n+1): if j>i: break if i==1: dp[i][j]=arr[0] else: dp[i][j]=max(dp[i-1][j],dp[i-2][j-1]+arr[i-1]) return dp[p][n] return max(summax(s1),summax(s2))
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: original = slices slices = slices[:-1] dp = [[0 for j in range(len(original) // 3 + 1)] for i in range(len(slices) + 1)] for j in range(1, len(original) // 3 + 1): dp[1][j] = slices[0] for j in range(1, len(dp[0])): for i in range(2, len(dp)): dp[i][j] = max(dp[i - 1][j], dp[i - 2][j - 1] + slices[i - 1], dp[i][j]) ans = dp[-1][-1] slices = original[1:] dp = [[0 for j in range(len(original) // 3 + 1)] for i in range(len(slices) + 1)] for j in range(1, len(original) // 3 + 1): dp[1][j] = slices[0] for j in range(1, len(dp[0])): for i in range(2, len(dp)): dp[i][j] = max(dp[i - 1][j], dp[i - 2][j - 1] + slices[i - 1], dp[i][j]) ans = max(ans, dp[-1][-1]) return ans
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution(object): def maxSizeSlices(self, A): N = len(A) A.extend(A) NINF = float('-inf') @lru_cache(None) def dp(i, j, rem): if rem == 0: return 0 elif i > j: return NINF else: return max(dp(i+2, j, rem-1) + A[i], dp(i+1, j, rem)) return max(A[0] + dp(2, N - 2, N // 3 - 1), dp(1, N - 1, N // 3))
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: @lru_cache(None) def dp(i, remaining, version): if i > len(slices) - version: return 0 if remaining == 0: return 0 else: return max(dp(i + 1, remaining, version), slices[i] + dp(i + 2, remaining - 1, version)) return max(dp(1, len(slices) // 3, 1), dp(0, len(slices) // 3, 2))
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, w: List[int]) -> int: k = len(w)//3 dp1 = [[0]*(len(w)) for _ in range(k+1)] dp2 = [[0]*(len(w)) for _ in range(k+1)] for n in range(1,k+1): for i in range(1,len(w)): if i==1: dp1[n][i] = w[i-1] dp2[n][i] = w[i] continue dp1[n][i] = max(dp1[n-1][i-2]+w[i-1],dp1[n][i-1]) dp2[n][i] = max(dp2[n-1][i-2]+w[i],dp2[n][i-1]) return max(dp1[-1][-1],dp2[-1][-1])
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: N = len(slices) @lru_cache(None) def dp(i, k, d): if 3*k == N: return 0 if i >= N-d: return -math.inf return max(slices[i] + dp(i+2, k+1, d), dp(i+1, k, d)) return max(slices[0] + dp(2, 1, 1), dp(1, 0, 0))
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: # find a subseq in circle without disjoint element.... n = len(slices) // 3 def get_maxsubseq(pieces): #dp(i, j) = max(dp(i-1, j-2) + pieces[j], dp(i, j-1)) m = len(pieces) dp = {} for i in range(1, n+1): tdp = {} for j in range(m): tdp[j] = max(dp.get(j-2, 0) + pieces[j], tdp.get(j-1, 0)) dp = tdp return dp[m-1] return max(get_maxsubseq(slices[1:]), get_maxsubseq(slices[:-1]))
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: m = len(slices) slices1 = slices[0:m-1] slices2 = slices[1:] n = m // 3 def helper(arr, n): m = len(arr) # dp[i][j] represents max sum when pick j elements from array of length i dp = [[0 for j in range(n + 1)] for i in range(m + 1)] for i in range(1,m + 1): for j in range(1, n + 1): if i == 1: dp[i][j] = arr[0] else: dp[i][j] = max(dp[i - 1][j], dp[i - 2][j - 1] + arr[i - 1]) return dp[m][n] return max(helper(slices1, n), helper(slices2, n))
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: # select 1 -> max of selecting n-1 from 2, 3n-1 # not select 1 -> max of selecting n from 2, 3n # a table to fill: (either selected or not) # 1, 2, 3, ... 3n # pos #0 maxSum #1 #2 # #n #num selected N = len(slices) // 3 dpOn = [[-1 for i in range(3 * N)] for j in range(N+1)] dpOff = [[-1 for i in range(3 * N)] for j in range(N+1)] # first 1 selected dpOn[1][0] = slices[0] for i in range(1, 3*N): dpOff[0][i] = 0 for i in range(1, 3*N): for j in range(1, N+1): dpOff[j][i] = max(dpOn[j][i-1], dpOff[j][i-1]) if dpOff[j-1][i-1] == -1: dpOn[j][i] = -1 else: dpOn[j][i] = dpOff[j-1][i-1] + slices[i] maxVal = dpOff[N][3*N-1] dpOn = [[-1 for i in range(3 * N)] for j in range(N+1)] dpOff = [[-1 for i in range(3 * N)] for j in range(N+1)] # first 1 not selected for i in range(0, 3*N): dpOff[0][i] = 0 for i in range(1, 3*N): for j in range(1, N+1): dpOff[j][i] = max(dpOn[j][i-1], dpOff[j][i-1]) if dpOff[j-1][i-1] == -1: dpOn[j][i] = -1 else: dpOn[j][i] = dpOff[j-1][i-1] + slices[i] maxVal = max(maxVal, dpOn[N][3*N-1], dpOff[N][3*N-1]) return maxVal
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
from functools import * class Solution(object): def maxSizeSlices(self, slices): @lru_cache(None) def dp(start, end, k): if k ==0: return 0 if k == 1: return max(slices[start:end+1]) if end-start+1<k*2-1: return -float('inf') return max(dp(start+2, end, k-1)+slices[start], dp(start+1, end, k)) n = len(slices)//3 return max(dp(0, len(slices)-2, n), dp(1, len(slices)-1, n))
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
from typing import List, Dict, Set, Optional from enum import Enum from functools import lru_cache class Person(Enum): ME = 0 ALICE = 1 BOB = 2 class DoublyLinkedListNode: def __init__(self, val: int) -> None: self.val = val self.prev = None self.next = None class Solution: def maxSizeSlices(self, slices: List[int]) -> int: @lru_cache(None) def dfs(pizza_slice: int, max_slice: int, level: int) -> int: if level == len(slices) / 3: return 0 if pizza_slice > max_slice: return 0 return max( dfs(pizza_slice + 2, max_slice, level + 1) + slices[pizza_slice], dfs(pizza_slice + 1, max_slice, level), ) return max(dfs(1, len(slices) - 1, 0), dfs(0, len(slices) - 2, 0)) def maxSizeSlicesBruteForce(self, slices: List[int]) -> int: slices_nodes = [DoublyLinkedListNode(pos) for pos in range(len(slices))] for pizza_slice_pos in range(len(slices)): prev_pizza_slice_pos = (pizza_slice_pos - 1) % len(slices) next_pizza_slice_pos = (pizza_slice_pos + 1) % len(slices) pizza_slice = slices_nodes[pizza_slice_pos] prev_pizza_slice = slices_nodes[prev_pizza_slice_pos] next_pizza_slice = slices_nodes[next_pizza_slice_pos] prev_pizza_slice.next = pizza_slice pizza_slice.prev = prev_pizza_slice pizza_slice.next = next_pizza_slice next_pizza_slice.prev = pizza_slice def dfs(pizza_slices_left: Set[int]) -> int: result = 0 for pizza_slice_pos in list(pizza_slices_left): pizza_slice = slices_nodes[pizza_slice_pos] prev_pizza_slice = pizza_slice.prev next_pizza_slice = pizza_slice.__next__ prev_prev_pizza_slice = prev_pizza_slice.prev next_next_pizza_slice = next_pizza_slice.__next__ prev_prev_pizza_slice.next = next_next_pizza_slice next_next_pizza_slice.prev = prev_prev_pizza_slice pizza_slices_left.remove(pizza_slice.val) pizza_slices_left.remove(prev_pizza_slice.val) pizza_slices_left.remove(next_pizza_slice.val) result = max(result, dfs(pizza_slices_left) + slices[pizza_slice.val]) pizza_slices_left.add(pizza_slice.val) pizza_slices_left.add(prev_pizza_slice.val) pizza_slices_left.add(next_pizza_slice.val) prev_prev_pizza_slice.next = prev_pizza_slice next_next_pizza_slice.prev = next_pizza_slice return result return dfs(set(range(len(slices)))) class TestSolution: def setup(self) -> None: self.sol = Solution() def test_case1(self) -> None: assert self.sol.maxSizeSlices([1,2,3,4,5,6]) == 10 def test_case2(self) -> None: assert self.sol.maxSizeSlices([6,3,1,2,6,2,4,3,10,4,1,4,6,5,5,3,4,7,6,5,8,7,3,8,8,1,7,1,7,8]) == 10
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: N = len(slices) target = N//3 dp = [[-1 for x in range(target)] for y in range(N)] def dfs(idx: int, cnt: int) -> int: if cnt >= target or idx >= N: return 0 if dp[idx][cnt] == -1: dp[idx][cnt] = max(dfs(idx+1, cnt), slices[idx]+dfs(idx+2, cnt+1)) return dp[idx][cnt] result = dfs(1, 0) dp = [[-1 for x in range(target)] for y in range(N)] N -= 1 result = max(result, dfs(0, 0)) return result
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: n=len(slices) dp=[[0 for j in range(n//3)] for i in range(n)] dp[0][0]=slices[0] for i in range(1,n): dp[i][0]=max(dp[i-1][0],slices[i]) for i in range(2,n): for j in range(1,min(i//2+1,n//3)): dp[i][j]=max(dp[i-1][j],dp[i-2][j-1]+slices[i]) mx=0 for i in range(n-1): mx=max(mx,dp[i][-1]) for i in range(n): for j in range(n//3): dp[i][j]=0 for i in range(1,n): dp[i][0]=max(dp[i-1][0],slices[i]) for i in range(2,n): for j in range(1,min(i//2+1,n//3)): dp[i][j]=max(dp[i-1][j],dp[i-2][j-1]+slices[i]) mx=max(mx,dp[-1][-1]) return mx
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, w: List[int]) -> int: n_picks = len(w)//3 dp1 = [[0 for _ in range(len(w))] for _ in range(n_picks+1)] dp2 = [[0 for _ in range(len(w))] for _ in range(n_picks+1)] for i in range(1,n_picks+1): for j in range(1,len(w)): if j == 1: dp1[i][j] = w[j-1] dp2[i][j] = w[j] continue dp1[i][j] = max(w[j-1] + dp1[i-1][j-2],dp1[i][j-1]) dp2[i][j] = max(w[j] + dp2[i-1][j-2],dp2[i][j-1]) return max(dp1[n_picks][len(w)-1],dp2[n_picks][len(w)-1])
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
from functools import lru_cache class Solution: def maxSizeSlices(self, w: List[int]) -> int: n = len(w) k = n // 3 dp1 = [[0] * n for _ in range(k + 1)] dp2 = [[0] * n for _ in range(k + 1)] for i in range(1, k + 1): dp1[i][1] = w[0] dp2[i][1] = w[1] for j in range(2, len(w)): dp1[i][j] = max(dp1[i - 1][j - 2] + w[j - 1], dp1[i][j - 1]) dp2[i][j] = max(dp2[i - 1][j - 2] + w[j], dp2[i][j - 1]) return max(dp1[-1][-1], dp2[-1][-1])
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: n = len(slices) memo = {} def solve(i, j, k): if k == 0: return 0 elif i > j: return 0 elif (i, j, k) in memo: return memo[(i, j, k)] memo[(i, j, k)] = max(slices[i]+solve(i+2, j, k-1), solve(i+1, j, k)) return memo[(i, j, k)] return max(solve(0, n-2, n//3), solve(1, n-1, n//3))
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: N = len(slices) @lru_cache(None) def rec(cur, taken, avoid_last): if taken * 3 > N: return -math.inf if cur >= N: return 0 if taken * 3 == N else -math.inf ans = rec(cur+1, taken, avoid_last) if avoid_last and cur == N-1: return ans ans = max(ans, rec(cur+2, taken+1, avoid_last | (cur == 0)) + slices[cur]) return ans return rec(0, 0, False)
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: @lru_cache(None) def dp(i, j, k): if k == 0: return 0 elif i >= j: return -math.inf else: return max( slices[i] + dp(i + 2, j, k - 1), dp(i + 1, j, k) ) n = len(slices) s = n // 3 return max( dp(1, n, s), dp(0, n - 1, s) )
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, slices: List[int]) -> int: n = len(slices) // 3 if n == 1: return max(slices) @lru_cache(None) def process(f, p, i, k): if i == 0: return slices[0] if f == 1 else 0 if p == 1: return process(f, 0, i-1, k) else: if (i == 1 and f == 1) or k == 0: return process(f, 0, i-1, k) else: return max(process(f, 0, i-1, k), slices[i]+process(f, 1, i-1, k-1)) return max(process(0, 0, 3*n-1, n), process(1, 1, 3*n-1, n-1))
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
from typing import List, Dict, Set, Optional from enum import Enum from functools import lru_cache class Person(Enum): ME = 0 ALICE = 1 BOB = 2 class DoublyLinkedListNode: def __init__(self, val: int) -> None: self.val = val self.prev = None self.next = None class Solution: def maxSizeSlices(self, slices: List[int]) -> int: levels = len(slices) // 3 + 1 result = 0 for start, stop in ((0, len(slices) - 1), (1, len(slices))): dp = [[0] * levels for _ in range(len(slices) + 2)] for pizza_slice in reversed(list(range(start, stop))): for level in range(levels): if pizza_slice + 2 < len(dp) and level < levels - 1: dp[pizza_slice][level] = max( dp[pizza_slice][level], dp[pizza_slice + 2][level + 1] + slices[pizza_slice], ) dp[pizza_slice][level] = max( dp[pizza_slice][level], dp[pizza_slice + 1][level], ) result = max(result, dp[start][0]) return result def maxSizeSlicesTopDown(self, slices: List[int]) -> int: @lru_cache(None) def dfs(pizza_slice: int, max_slice: int, level: int) -> int: if level == len(slices) / 3: return 0 if pizza_slice > max_slice: return 0 return max( dfs(pizza_slice + 2, max_slice, level + 1) + slices[pizza_slice], dfs(pizza_slice + 1, max_slice, level), ) return max(dfs(1, len(slices) - 1, 0), dfs(0, len(slices) - 2, 0)) def maxSizeSlicesBruteForce(self, slices: List[int]) -> int: slices_nodes = [DoublyLinkedListNode(pos) for pos in range(len(slices))] for pizza_slice_pos in range(len(slices)): prev_pizza_slice_pos = (pizza_slice_pos - 1) % len(slices) next_pizza_slice_pos = (pizza_slice_pos + 1) % len(slices) pizza_slice = slices_nodes[pizza_slice_pos] prev_pizza_slice = slices_nodes[prev_pizza_slice_pos] next_pizza_slice = slices_nodes[next_pizza_slice_pos] prev_pizza_slice.next = pizza_slice pizza_slice.prev = prev_pizza_slice pizza_slice.next = next_pizza_slice next_pizza_slice.prev = pizza_slice def dfs(pizza_slices_left: Set[int]) -> int: result = 0 for pizza_slice_pos in list(pizza_slices_left): pizza_slice = slices_nodes[pizza_slice_pos] prev_pizza_slice = pizza_slice.prev next_pizza_slice = pizza_slice.__next__ prev_prev_pizza_slice = prev_pizza_slice.prev next_next_pizza_slice = next_pizza_slice.__next__ prev_prev_pizza_slice.next = next_next_pizza_slice next_next_pizza_slice.prev = prev_prev_pizza_slice pizza_slices_left.remove(pizza_slice.val) pizza_slices_left.remove(prev_pizza_slice.val) pizza_slices_left.remove(next_pizza_slice.val) result = max(result, dfs(pizza_slices_left) + slices[pizza_slice.val]) pizza_slices_left.add(pizza_slice.val) pizza_slices_left.add(prev_pizza_slice.val) pizza_slices_left.add(next_pizza_slice.val) prev_prev_pizza_slice.next = prev_pizza_slice next_next_pizza_slice.prev = next_pizza_slice return result return dfs(set(range(len(slices)))) class TestSolution: def setup(self) -> None: self.sol = Solution() def test_case1(self) -> None: assert self.sol.maxSizeSlices([1,2,3,4,5,6]) == 10 def test_case2(self) -> None: assert self.sol.maxSizeSlices([6,3,1,2,6,2,4,3,10,4,1,4,6,5,5,3,4,7,6,5,8,7,3,8,8,1,7,1,7,8]) == 10
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick next slice in anti clockwise direction of your pick.  Your friend Bob will pick next slice in clockwise direction of your pick. Repeat until there are no more slices of pizzas. Sizes of Pizza slices is represented by circular array slices in clockwise direction. Return the maximum possible sum of slice sizes which you can have.   Example 1: Input: slices = [1,2,3,4,5,6] Output: 10 Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6. Example 2: Input: slices = [8,9,8,6,1,1] Output: 16 Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8. Example 3: Input: slices = [4,1,2,5,8,3,1,9,7] Output: 21 Example 4: Input: slices = [3,1,2] Output: 3   Constraints: 1 <= slices.length <= 500 slices.length % 3 == 0 1 <= slices[i] <= 1000
class Solution: def maxSizeSlices(self, w: List[int]) -> int: n = len(w) k = n // 3 results = [0, 0] for offset in range(2): cur = [0] * n prev = [0] * n for _ in range(k): cur[1] = w[offset] for j in range(2, n): cur[j] = max(prev[j - 2] + w[j - 1 + offset], cur[j - 1]) prev[:] = cur cur[:] = [0] * n results[offset] = prev[-1] return max(results)
Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2 or 3 stones from the first remaining stones in the row. The score of each player is the sum of values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally. Return "Alice" if Alice will win, "Bob" if Bob will win or "Tie" if they end the game with the same score.   Example 1: Input: values = [1,2,3,7] Output: "Bob" Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins. Example 2: Input: values = [1,2,3,-9] Output: "Alice" Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score. If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. The next move Alice will take the pile with value = -9 and lose. If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. The next move Alice will take the pile with value = -9 and also lose. Remember that both play optimally so here Alice will choose the scenario that makes her win. Example 3: Input: values = [1,2,3,6] Output: "Tie" Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose. Example 4: Input: values = [1,2,3,-1,-2,-3,7] Output: "Alice" Example 5: Input: values = [-1,-2,-3] Output: "Tie"   Constraints: 1 <= values.length <= 50000 -1000 <= values[i] <= 1000
class Solution: def stoneGameIII(self, stoneValue: List[int]) -> str: A = stoneValue dp = [0] * 3 for i in range(len(A) - 1, -1, -1): dp[i % 3] = max(sum(A[i:i + k]) - dp[(i + k) % 3] for k in (1, 2, 3)) if dp[0] > 0: return 'Alice' elif dp[0] < 0: return 'Bob' else: return 'Tie'
Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2 or 3 stones from the first remaining stones in the row. The score of each player is the sum of values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally. Return "Alice" if Alice will win, "Bob" if Bob will win or "Tie" if they end the game with the same score.   Example 1: Input: values = [1,2,3,7] Output: "Bob" Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins. Example 2: Input: values = [1,2,3,-9] Output: "Alice" Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score. If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. The next move Alice will take the pile with value = -9 and lose. If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. The next move Alice will take the pile with value = -9 and also lose. Remember that both play optimally so here Alice will choose the scenario that makes her win. Example 3: Input: values = [1,2,3,6] Output: "Tie" Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose. Example 4: Input: values = [1,2,3,-1,-2,-3,7] Output: "Alice" Example 5: Input: values = [-1,-2,-3] Output: "Tie"   Constraints: 1 <= values.length <= 50000 -1000 <= values[i] <= 1000
from itertools import accumulate class Solution: def stoneGameIII(self, sv: List[int]) -> str: m = len(sv) dp = [-sys.maxsize] * m dp.append(0) ps = list(accumulate(sv)) sm = sum(sv) for i in range(m-1, -1, -1): if i == m-1: dp[i] = sv[i] elif i == m-2: dp[i] = max(dp[i], sv[i] + (ps[-1] - ps[i] - dp[i+1])) dp[i] = max(dp[i], sv[i] + sv[i+1]) else: dp[i] = max(dp[i], sv[i] + (ps[-1] - ps[i] - dp[i+1])) dp[i] = max(dp[i], sv[i] + sv[i+1] + (ps[-1] - ps[i+1] - dp[i+2])) dp[i] = max(dp[i], sv[i] + sv[i+1] + sv[i+2] + (ps[-1] - ps[i+2] - dp[i+3])) if dp[0] * 2 == sm: return 'Tie' if dp[0] * 2 > sm: return 'Alice' return 'Bob'
Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2 or 3 stones from the first remaining stones in the row. The score of each player is the sum of values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally. Return "Alice" if Alice will win, "Bob" if Bob will win or "Tie" if they end the game with the same score.   Example 1: Input: values = [1,2,3,7] Output: "Bob" Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins. Example 2: Input: values = [1,2,3,-9] Output: "Alice" Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score. If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. The next move Alice will take the pile with value = -9 and lose. If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. The next move Alice will take the pile with value = -9 and also lose. Remember that both play optimally so here Alice will choose the scenario that makes her win. Example 3: Input: values = [1,2,3,6] Output: "Tie" Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose. Example 4: Input: values = [1,2,3,-1,-2,-3,7] Output: "Alice" Example 5: Input: values = [-1,-2,-3] Output: "Tie"   Constraints: 1 <= values.length <= 50000 -1000 <= values[i] <= 1000
class Solution: def stoneGameIII(self, stoneValue: List[int]) -> str: dp = [0] * 3 for i in range(len(stoneValue) - 1, -1, -1): dp[i % 3] = max(sum(stoneValue[i:i + k]) - dp[(i + k) % 3] for k in (1, 2, 3)) if dp[0] == 0: return 'Tie' elif dp[0] > 0: return 'Alice' else: return 'Bob'
Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2 or 3 stones from the first remaining stones in the row. The score of each player is the sum of values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally. Return "Alice" if Alice will win, "Bob" if Bob will win or "Tie" if they end the game with the same score.   Example 1: Input: values = [1,2,3,7] Output: "Bob" Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins. Example 2: Input: values = [1,2,3,-9] Output: "Alice" Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score. If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. The next move Alice will take the pile with value = -9 and lose. If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. The next move Alice will take the pile with value = -9 and also lose. Remember that both play optimally so here Alice will choose the scenario that makes her win. Example 3: Input: values = [1,2,3,6] Output: "Tie" Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose. Example 4: Input: values = [1,2,3,-1,-2,-3,7] Output: "Alice" Example 5: Input: values = [-1,-2,-3] Output: "Tie"   Constraints: 1 <= values.length <= 50000 -1000 <= values[i] <= 1000
class Solution: def stoneGameIII(self, stoneValue: List[int]) -> str: n = len(stoneValue) # cumsum = [0]*(n+1) # for i in range(1,n+1): # cumsum[i] = cumsum[i-1] + stoneValue[i-1] # @functools.lru_cache(None) # def helper(i, turn): # if turn == 0: # if i == n: # return 0 # if i == n-1: # return stoneValue[-1] # return max([cumsum[i+k]-cumsum[i] + helper(i+k,1) for k in [1,2,3] if i+k <= n]) # else: # if i == n: # return 0 # if i == n-1: # return 0 # return min([helper(i+k,0) for k in [1,2,3] if i+k <= n]) # c = helper(0,0) # if c > sum(stoneValue) / 2.0: # return 'Alice' # elif c == sum(stoneValue) / 2.0: # return 'Tie' # else: # return 'Bob' A = stoneValue dp = [0] * 3 for i in range(n - 1, -1, -1): dp[i % 3] = max(sum(A[i:i + k]) - dp[(i + k) % 3] for k in (1, 2, 3)) c = dp[0] if c > 0: return 'Alice' elif c == 0: return 'Tie' else: return 'Bob'
Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2 or 3 stones from the first remaining stones in the row. The score of each player is the sum of values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally. Return "Alice" if Alice will win, "Bob" if Bob will win or "Tie" if they end the game with the same score.   Example 1: Input: values = [1,2,3,7] Output: "Bob" Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins. Example 2: Input: values = [1,2,3,-9] Output: "Alice" Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score. If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. The next move Alice will take the pile with value = -9 and lose. If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. The next move Alice will take the pile with value = -9 and also lose. Remember that both play optimally so here Alice will choose the scenario that makes her win. Example 3: Input: values = [1,2,3,6] Output: "Tie" Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose. Example 4: Input: values = [1,2,3,-1,-2,-3,7] Output: "Alice" Example 5: Input: values = [-1,-2,-3] Output: "Tie"   Constraints: 1 <= values.length <= 50000 -1000 <= values[i] <= 1000
class Solution: def stoneGameIII(self, arr: List[int]) -> str: ln, dp = len(arr), [float('-inf') for _ in range(len(arr))] dp.append(0) for i in range(ln-1, -1,-1): sm =0 for j in range(i, min(ln, i+3)): sm +=arr[j] dp[i] = max(dp[i], sm - dp[j+1]) if dp[0]>0: return 'Alice' elif dp[0]<0: return 'Bob' return 'Tie'
Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2 or 3 stones from the first remaining stones in the row. The score of each player is the sum of values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally. Return "Alice" if Alice will win, "Bob" if Bob will win or "Tie" if they end the game with the same score.   Example 1: Input: values = [1,2,3,7] Output: "Bob" Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins. Example 2: Input: values = [1,2,3,-9] Output: "Alice" Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score. If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. The next move Alice will take the pile with value = -9 and lose. If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. The next move Alice will take the pile with value = -9 and also lose. Remember that both play optimally so here Alice will choose the scenario that makes her win. Example 3: Input: values = [1,2,3,6] Output: "Tie" Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose. Example 4: Input: values = [1,2,3,-1,-2,-3,7] Output: "Alice" Example 5: Input: values = [-1,-2,-3] Output: "Tie"   Constraints: 1 <= values.length <= 50000 -1000 <= values[i] <= 1000
class Solution: def stoneGameIII(self, stoneValue: List[int]) -> str: n = len(stoneValue) dp = [float('-inf')] * n # max score after i dp[-1] = stoneValue[-1] dp.append(0) for i in range(n-2, -1, -1): temp = 0 for j in range(3): if i+j+1>n: break temp += stoneValue[i+j] dp[i] = max(dp[i], temp-dp[i+j+1]) if dp[0]>0: return 'Alice' elif dp[0]<0: return 'Bob' return 'Tie'
Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2 or 3 stones from the first remaining stones in the row. The score of each player is the sum of values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally. Return "Alice" if Alice will win, "Bob" if Bob will win or "Tie" if they end the game with the same score.   Example 1: Input: values = [1,2,3,7] Output: "Bob" Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins. Example 2: Input: values = [1,2,3,-9] Output: "Alice" Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score. If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. The next move Alice will take the pile with value = -9 and lose. If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. The next move Alice will take the pile with value = -9 and also lose. Remember that both play optimally so here Alice will choose the scenario that makes her win. Example 3: Input: values = [1,2,3,6] Output: "Tie" Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose. Example 4: Input: values = [1,2,3,-1,-2,-3,7] Output: "Alice" Example 5: Input: values = [-1,-2,-3] Output: "Tie"   Constraints: 1 <= values.length <= 50000 -1000 <= values[i] <= 1000
class Solution: def stoneGameIII(self, S: List[int]) -> str: n = len(S) dp = [0] * n for i in range(n)[::-1]: dp[i] = max(sum(S[i:i+k]) - (dp[i+k] if i + k < n else 0) for k in (1,2,3) ) if dp[0] > 0: return 'Alice' elif dp[0] < 0: return 'Bob' else: return 'Tie'
Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2 or 3 stones from the first remaining stones in the row. The score of each player is the sum of values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally. Return "Alice" if Alice will win, "Bob" if Bob will win or "Tie" if they end the game with the same score.   Example 1: Input: values = [1,2,3,7] Output: "Bob" Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins. Example 2: Input: values = [1,2,3,-9] Output: "Alice" Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score. If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. The next move Alice will take the pile with value = -9 and lose. If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. The next move Alice will take the pile with value = -9 and also lose. Remember that both play optimally so here Alice will choose the scenario that makes her win. Example 3: Input: values = [1,2,3,6] Output: "Tie" Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose. Example 4: Input: values = [1,2,3,-1,-2,-3,7] Output: "Alice" Example 5: Input: values = [-1,-2,-3] Output: "Tie"   Constraints: 1 <= values.length <= 50000 -1000 <= values[i] <= 1000
class Solution: def stoneGameIII(self, nums: List[int]) -> str: n = len(nums) total = sum(nums) presum = [nums[-1]] if n > 1: presum.insert(0, nums[-2]+presum[0]) nums[-2] = max(nums[-2], presum[0]) if n > 2: presum.insert(0, nums[-3]+presum[0]) nums[-3] = max([nums[-3] + presum[1] - nums[-2], nums[-3] + presum[1] - presum[2], presum[0]]) for i in range(n-4, -1, -1): get_one = nums[i] + presum[0] - nums[i+1] get_two = nums[i] + presum[0] - presum[1] + presum[1] - nums[i+2] get_three = nums[i] + presum[0] - presum[2] + presum[2] - nums[i+3] presum.pop() presum.insert(0, presum[0] + nums[i]) nums[i] = max([get_one, get_two, get_three]) # print(nums) if nums[0] == presum[0]/2: return 'Tie' elif nums[0] > presum[0]/2: return 'Alice' return 'Bob'
Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2 or 3 stones from the first remaining stones in the row. The score of each player is the sum of values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally. Return "Alice" if Alice will win, "Bob" if Bob will win or "Tie" if they end the game with the same score.   Example 1: Input: values = [1,2,3,7] Output: "Bob" Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins. Example 2: Input: values = [1,2,3,-9] Output: "Alice" Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score. If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. The next move Alice will take the pile with value = -9 and lose. If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. The next move Alice will take the pile with value = -9 and also lose. Remember that both play optimally so here Alice will choose the scenario that makes her win. Example 3: Input: values = [1,2,3,6] Output: "Tie" Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose. Example 4: Input: values = [1,2,3,-1,-2,-3,7] Output: "Alice" Example 5: Input: values = [-1,-2,-3] Output: "Tie"   Constraints: 1 <= values.length <= 50000 -1000 <= values[i] <= 1000
class Solution: def stoneGameIII(self, stns: List[int]) -> str: stns.reverse() if len(stns)>1: ans = [0, stns[0], stns[1]+abs(stns[0])] for i in range(2, len(stns)): ans.append(max(stns[i]+stns[i-1]+stns[i-2]-ans[-3], stns[i]+stns[i-1]-ans[-2], stns[i]-ans[-1])) else: ans = stns return 'Alice' if ans[-1]>0 else 'Tie' if ans[-1]==0 else 'Bob'
Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2 or 3 stones from the first remaining stones in the row. The score of each player is the sum of values of the stones taken. The score of each player is 0 initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob play optimally. Return "Alice" if Alice will win, "Bob" if Bob will win or "Tie" if they end the game with the same score.   Example 1: Input: values = [1,2,3,7] Output: "Bob" Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins. Example 2: Input: values = [1,2,3,-9] Output: "Alice" Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score. If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. The next move Alice will take the pile with value = -9 and lose. If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. The next move Alice will take the pile with value = -9 and also lose. Remember that both play optimally so here Alice will choose the scenario that makes her win. Example 3: Input: values = [1,2,3,6] Output: "Tie" Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose. Example 4: Input: values = [1,2,3,-1,-2,-3,7] Output: "Alice" Example 5: Input: values = [-1,-2,-3] Output: "Tie"   Constraints: 1 <= values.length <= 50000 -1000 <= values[i] <= 1000
class Solution: def stoneGameIII(self, A: List[int]) -> str: n = len(A) dp = [-float('inf')]*n A.reverse() for i, x in enumerate(A): adding = 0 for j in range(3): if i-j>=0: adding += A[i-j] dp[i] = max(dp[i], adding - (dp[i-j-1] if i-j>=1 else 0)) if dp[-1] < 0: return 'Bob' return 'Tie' if dp[-1] == 0 else 'Alice'