Datasets:

inputs
stringlengths
50
14k
targets
stringlengths
4
655k
In an array A of 0s and 1s, how many non-empty subarrays have sum S?   Example 1: Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]   Note: A.length <= 30000 0 <= S <= A.length A[i] is either 0 or 1.
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int: p = [0] for i in A: p.append(p[-1]+i) cnt = collections.Counter() res = 0 for i in p: res += cnt[i] cnt[i+S] += 1 return res
In an array A of 0s and 1s, how many non-empty subarrays have sum S?   Example 1: Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]   Note: A.length <= 30000 0 <= S <= A.length A[i] is either 0 or 1.
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int: d = defaultdict(int) d[0] = 1 psum = res = 0 for a in A: psum += a res += d[psum - S] d[psum]+=1 return res
In an array A of 0s and 1s, how many non-empty subarrays have sum S?   Example 1: Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]   Note: A.length <= 30000 0 <= S <= A.length A[i] is either 0 or 1.
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int: P = [0] for x in A: P.append(P[-1] + x) count = collections.Counter() ans = 0 for x in P: ans += count[x] count[x + S] += 1 return ans
In an array A of 0s and 1s, how many non-empty subarrays have sum S?   Example 1: Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]   Note: A.length <= 30000 0 <= S <= A.length A[i] is either 0 or 1.
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int: numToFreq = {} numToFreq[0] = 1 now_sum = 0 ans = 0 for num in A: now_sum += num if now_sum == S: ans += (numToFreq[0]) elif now_sum > S: if now_sum - S in numToFreq: ans += (numToFreq[now_sum - S]) if now_sum not in numToFreq: numToFreq[now_sum] = 0 numToFreq[now_sum] += 1 return ans
In an array A of 0s and 1s, how many non-empty subarrays have sum S?   Example 1: Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]   Note: A.length <= 30000 0 <= S <= A.length A[i] is either 0 or 1.
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int: n = len(A) def num_subar_at_most(lim): subarr_ct = 0 r_sum = 0 li = 0 for ri in range(n): r_sum += A[ri] while li <= ri and r_sum > lim: r_sum -= A[li] li += 1 subarr_ct += ri - li + 1 return subarr_ct return num_subar_at_most(S) - num_subar_at_most(S - 1)
In an array A of 0s and 1s, how many non-empty subarrays have sum S?   Example 1: Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]   Note: A.length <= 30000 0 <= S <= A.length A[i] is either 0 or 1.
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int: cumsum = 0 dic = {0:[-1]} ans = 0 for i,num in enumerate(A): cumsum += num dic[cumsum] = dic.get(cumsum,[]) + [i] ans += len(dic.get(cumsum-S,[])) #print(ans,dic) return ans - (0 if S else len(A))
In an array A of 0s and 1s, how many non-empty subarrays have sum S?   Example 1: Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]   Note: A.length <= 30000 0 <= S <= A.length A[i] is either 0 or 1.
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int: ans=0 il,ih,sl,sh=0,0,0,0 for j,x in enumerate(A): sl+=x while il<j and sl>S: sl-=A[il] il+=1 sh+=x while ih<j and (sh>S or sh==S and not A[ih]): sh-=A[ih] ih+=1 if sl==S: ans+=ih-il+1 return ans
In an array A of 0s and 1s, how many non-empty subarrays have sum S?   Example 1: Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]   Note: A.length <= 30000 0 <= S <= A.length A[i] is either 0 or 1.
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int: count = 0 output = 0 left = 0 for right in range(len(A)): S -= A[right] if A[right] == 1: count = 0 while left <= right and S <= 0: if S == 0: count += 1 S += A[left] left += 1 output += count return output
In an array A of 0s and 1s, how many non-empty subarrays have sum S?   Example 1: Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]   Note: A.length <= 30000 0 <= S <= A.length A[i] is either 0 or 1.
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int: def helper(k): if k < 0: return 0 num = 0 i = 0 for j in range(len(A)): k -= A[j] while k < 0: k += A[i] i += 1 num += j-i+1 return num return helper(S)-helper(S-1)
In an array A of 0s and 1s, how many non-empty subarrays have sum S?   Example 1: Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]   Note: A.length <= 30000 0 <= S <= A.length A[i] is either 0 or 1.
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int: c = collections.Counter({0: 1}) psum = res = 0 for i in A: psum += i res += c[psum - S] c[psum] += 1 return res
In an array A of 0s and 1s, how many non-empty subarrays have sum S?   Example 1: Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]   Note: A.length <= 30000 0 <= S <= A.length A[i] is either 0 or 1.
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int: n = len(A) i, j, total, res = 0, 0, 0, 0 while j < n: total += A[j] while i < j and total > S: total -= A[i] i += 1 if total == S: res += 1 # There could be multiple 0 between i & j. k = i while k < j and A[k] == 0: k += 1 res += 1 j += 1 return res
In an array A of 0s and 1s, how many non-empty subarrays have sum S?   Example 1: Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]   Note: A.length <= 30000 0 <= S <= A.length A[i] is either 0 or 1.
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int: i, s, res, count = 0, 0, 0, 1 for j in range(len(A)): s += A[j] while i < j and (s > S or A[i] == 0): if A[i]: s -= A[i] count = 1 else: count += 1 i += 1 if s == S: res += count return res
In an array A of 0s and 1s, how many non-empty subarrays have sum S?   Example 1: Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]   Note: A.length <= 30000 0 <= S <= A.length A[i] is either 0 or 1.
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int: result = 0 left, right, count = 0, 0, 0 for right in range(len(A)): S -= A[right] if A[right] == 1: count = 0 while S <= 0 and left <= right: if S == 0: count += 1 S += A[left] left += 1 result += count return result
In an array A of 0s and 1s, how many non-empty subarrays have sum S?   Example 1: Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]   Note: A.length <= 30000 0 <= S <= A.length A[i] is either 0 or 1.
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int: count = {0:1} total = maxS = 0 for num in A: total += num maxS += count.get(total-S,0) count[total] = count.get(total,0)+1 return maxS
In an array A of 0s and 1s, how many non-empty subarrays have sum S?   Example 1: Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]   Note: A.length <= 30000 0 <= S <= A.length A[i] is either 0 or 1.
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int: ctr = collections.Counter({0:1}) prefix = res = 0 for a in A: prefix += a res += ctr[prefix - S] ctr[prefix] += 1 return res
In an array A of 0s and 1s, how many non-empty subarrays have sum S?   Example 1: Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]   Note: A.length <= 30000 0 <= S <= A.length A[i] is either 0 or 1.
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int: c = collections.Counter({0: 1}) psum = res = 0 for i in A: psum += i res += c[psum - S] c[psum] += 1 return res
Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1: Input: [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.   Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. Example 2: Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.   Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are   engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ tmax_profit = 0 rmax_profits = [0] * len(prices) rmax = -1 for ii in range(len(prices)-2, -1, -1): if (prices[rmax] - prices[ii] > rmax_profits[ii+1]): rmax_profits[ii] = prices[rmax] - prices[ii] else: rmax_profits[ii] = rmax_profits[ii+1] if prices[ii] > prices[rmax]: rmax = ii #print("rmax profit = {}".format(rmax_profits)) lmin = 0 lmax_profit = 0 for ii in range(1, len(prices)): profit = prices[ii]-prices[lmin] if profit > lmax_profit: lmax_profit = profit if prices[ii] < prices[lmin]: lmin = ii tprofit = lmax_profit if ii < len(prices)-1: tprofit += rmax_profits[ii+1] #print("ii = {}, rmax_profit = {}, lmax_profit = {}, tprofit = {}".format(ii, rmax_profits[ii], lmax_profit, tprofit)) if tprofit > tmax_profit: tmax_profit = tprofit return tmax_profit if tmax_profit>0 else 0
Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1: Input: [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.   Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. Example 2: Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.   Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are   engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices: return 0 n = len(prices) sell1 = 0 sell2 = 0 hold1 = -prices[0] hold2 = -prices[0] for i in range(1, n): sell2 = max(prices[i] + hold2, sell2) hold2 = max(sell1 - prices[i], hold2) sell1 = max(prices[i] + hold1, sell1) hold1 = max(-prices[i], hold1) #sell1[i] = max(sell1[i-1], prices[i] + hold1[i-1]) #hold1[i] = max(hold1[i-1], -prices[i]) #sell2[i] = max(prices[i] + hold2[i-1], sell2[i-1] ) #hold2[i] = max(sell1[i-1] - prices[i], hold2[i-1]) return sell2
Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1: Input: [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.   Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. Example 2: Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.   Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are   engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ #一天可以买卖2次 import sys min_v=-sys.maxsize buy1,buy2=min_v,min_v sell1,sell2=0,0 for i in prices: buy1=max(buy1,-i) #卖,分为本次不卖 或卖 sell1=max(sell1,buy1+i) buy2=max(buy2,sell1-i) #卖,分为本次不卖 或卖 sell2=max(sell2,buy2+i) return sell2
Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1: Input: [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.   Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. Example 2: Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.   Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are   engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
class Solution: def maxProfit(self, prices, k = 2): """ :type prices: List[int] :rtype: int """ if not prices: return 0 s1 = s2 = 0 b1 = b2 = -1000000000 for p in prices: b1 = max(b1, -p) s1 = max(s1, b1 + p) b2 = max(b2, s1 - p) s2 = max(s2, b2 + p) return s2
Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1: Input: [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.   Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. Example 2: Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.   Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are   engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices: return 0 sell_date = [0] * len(prices) min_price = prices[0] for i in range(1, len(prices)): sell_date[i] = max(sell_date[i - 1], prices[i] - min_price) min_price = min(prices[i], min_price) max_price, profit = prices[-1], 0 for i in range(len(prices) - 1, 0, -1): profit = max(profit, max_price - prices[i] + sell_date[i]) max_price = max(max_price, prices[i]) return profit
Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1: Input: [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.   Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. Example 2: Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.   Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are   engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
class Solution: def maxProfit(self, prices): length=len(prices) if length==0: return 0 f1=[0 for i in range(length)] f2=[0 for i in range(length)] minV=prices[0]; f1[0]=0 for i in range(1,length): minV=min(minV, prices[i]) f1[i]=max(f1[i-1],prices[i]-minV) maxV=prices[length-1]; f2[length-1]=0 for i in range(length-2,-1,-1): maxV=max(maxV,prices[i]) f2[i]=max(f2[i+1],maxV-prices[i]) res=0 for i in range(length): if f1[i]+f2[i]>res: res=f1[i]+f2[i] return res
Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1: Input: [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.   Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. Example 2: Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.   Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are   engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if len(prices)<2: return 0 buy = [] sell = [] for i in range(2): buy.append(-float("inf")) sell.append(-float("inf")) for i in prices: for j in range(2): if j== 0: buy[j] = max(buy[j], -i) sell[j] = max(sell[j], i+buy[j]) else: buy[j] = max(buy[j], sell[j-1]-i) sell[j] = max(sell[j], i+buy[j]) return sell[-1]
Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1: Input: [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.   Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. Example 2: Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.   Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are   engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
class Solution: def maxProfit(self,prices): k = 2 profit = [] n = len(prices) if n < 2: return 0 for i in range(k+1): profit.append([]) for j in range(n): profit[i].append(0) for i in range(1,k+1): tmpMax = profit[i-1][0] - prices[0] for j in range(n): profit[i][j] = max(profit[i][j-1], prices[j] + tmpMax) tmpMax = max(tmpMax,profit[i-1][j] - prices[j]) return profit[k][n-1]
Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1: Input: [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.   Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. Example 2: Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.   Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are   engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices: return 0 n = len(prices) sell1 = n * [0] hold1 = n * [0] sell2 = n * [0] hold2 = n * [0] hold1[0] = hold2[0] = -prices[0] for i in range(1, n): sell1[i] = max(sell1[i-1], prices[i] + hold1[i-1]) hold1[i] = max(hold1[i-1], -prices[i]) sell2[i] = max(prices[i] + hold2[i-1], sell2[i-1] ) hold2[i] = max(sell1[i-1] - prices[i], hold2[i-1]) return sell2[n-1]
Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1: Input: [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.   Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. Example 2: Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.   Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are   engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ left2right = [0] * len(prices) right2left = [0] * len(prices) dp = prices[:] max_profit = 0 for i in range(1, len(prices)): dp[i] = min(dp[i - 1], prices[i]) left2right[i] = max(left2right[i], prices[i] - dp[i]) max_profit = max(max_profit, prices[i] - dp[i]) dp = prices[:] for i in reversed(list(range(len(prices) - 1))): dp[i] = max(dp[i + 1], prices[i]) right2left[i] = max(right2left[i + 1], dp[i] - prices[i]) print(right2left) for i in range(len(prices) - 1): max_profit = max(max_profit, left2right[i] + right2left[i + 1]) return max_profit
Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1: Input: [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.   Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. Example 2: Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.   Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are   engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices:return 0 times,n = 2, len(prices) dp = [[0 for j in range(n)] for i in range(times)] buy_in = -prices[0] for i in range(1,n): dp[0][i] = max(dp[0][i-1], prices[i] + buy_in) buy_in = max(buy_in, -prices[i]) for k in range(1,times): buy_in = -prices[0] for j in range(1,n): dp[k][j] = max(buy_in + prices[j], dp[k][j-1]) buy_in = max(buy_in, dp[k-1][j] - prices[j]) return dp[-1][-1]
Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1: Input: [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.   Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. Example 2: Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.   Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are   engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices: return 0 buy1, sell1, buy2, sell2 = -prices[0], 0, -prices[0], 0 for p in prices: buy1 = max(buy1, -p) sell1 = max(sell1, buy1 + p) buy2 = max(buy2, sell1 - p) sell2 = max(sell2, buy2 + p) return sell2
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: # my solution ... 128 ms ... 99 % ... 17.9 MB ... 85 % # time: O(nlogn) # space: O(n) l2v = collections.defaultdict(list) for v,l in zip(values, labels): l2v[l].append(v) pool = [] for l in l2v: pool += sorted(l2v[l])[-use_limit:] return sum(sorted(pool)[-num_wanted:])
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: val_label = list(sorted(zip(values, labels), key = lambda x: x[0], reverse = True)) cnt_label = collections.Counter() chosen = 0 res = 0 for val, lab in val_label: if chosen < num_wanted: if cnt_label[lab] < use_limit: res += val chosen += 1 cnt_label[lab] += 1 return res
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Item: def __init__(self,label,value): self.label=label self.value=value class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: labelvalues=[] i=0 while i <len(values): labelvalues.append(Item(labels[i],values[i])) i+=1 lv=[] for item in labelvalues: heapq.heappush(lv,(-item.value,item.label)) countlabels=collections.defaultdict(int) maximum_sum=0 while num_wanted>0 and lv: max_value=heapq.heappop(lv) curr_max=max_value[0] curr_label_value=max_value[1] if countlabels.get(curr_label_value,0)<use_limit: countlabels[curr_label_value]+=1 maximum_sum-=curr_max num_wanted-=1 return maximum_sum
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: res = 0 heap = [[-v, i] for v, i in zip(values, labels)] heapq.heapify(heap) counter = Counter() while heap and num_wanted: v, i = heapq.heappop(heap) if counter[i] == use_limit: continue counter[i] += 1 res += -v num_wanted -= 1 return res
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: # # maintain max heap, get largest value for each label # # this brute force solution is O(nlogn + num_wanted) # values_by_label = defaultdict(list) # for i, val in enumerate(values): # heapq.heappush(values_by_label[labels[i]], -1 * val) # total = 0 # label_use_limit = defaultdict(int) # for label in values_by_label.keys(): # label_use_limit[label] = use_limit # for _ in range(num_wanted - 1, -1, -1): # max_num = -1 # for k, v in values_by_label.items(): # if label_use_limit[k] > 0 and len(v) > 0 and -1 * v[0] > max_num: # max_num = -1 * v[0] # best_label = k # if max_num != -1: # total += max_num # heapq.heappop(values_by_label[best_label]) # label_use_limit[best_label] -= 1 # return total ordered_values = [] # maxheap label_use_limit = defaultdict(int) for i, val in enumerate(values): heapq.heappush(ordered_values, (-1 * val, labels[i])) if labels[i] not in label_use_limit: label_use_limit[labels[i]] = use_limit total = 0 while len(ordered_values) > 0 and num_wanted > 0: top_elem = heapq.heappop(ordered_values) if label_use_limit[top_elem[1]] > 0: total += (-1 * top_elem[0]) label_use_limit[top_elem[1]] -= 1 num_wanted -= 1 return total
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: label2values = defaultdict(list) for value, label in zip(values, labels): label2values[label].append(value) all_top_nums = [] for values in list(label2values.values()): if use_limit >= len(values): top_nums = values else: top_nums = self.quick_select(use_limit, values) all_top_nums.extend(top_nums) if num_wanted >= len(all_top_nums): return sum(all_top_nums) return sum(self.quick_select(num_wanted, all_top_nums)) def quick_select(self, use_limit, nums): low = 0 high = len(nums) - 1 use_limit -= 1 while low <= high: pivot = self.partition(nums, low, high) if pivot == use_limit: return nums[:pivot + 1] elif pivot < use_limit: low = pivot + 1 else: high = pivot - 1 return nums def partition(self, nums, low, high): pivot = random.randint(low, high) self._swap(nums, pivot, high) pivot = low for i in range(low, high): if nums[i] > nums[high]: self._swap(nums, pivot, i) pivot += 1 self._swap(nums, pivot, high) return pivot def _swap(self, nums, i, j): nums[i], nums[j] = nums[j], nums[i] # Follow-up 1 # Do beter than O(nlogn). # Follow-up 2 # Can you do it in O(n) time? # What about using QuickSelect? # Steps: # Separate all elements by label => HashMap<Label, Array> m; # Use QuickSelect on each label's elements to find the largest m elements. # Merge the largest m elements from each label into an array # Use QuickSelect again on the resulting array to get the largest k elements. # *each step can be done in O(N).
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
import heapq class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: maxHeap = [] for value, label in zip(values, labels): print((value, label)) heappush(maxHeap, (-value, label)) labelFrequencies = {} maxSum = 0 numChosen = 0 while maxHeap and numChosen < num_wanted: value, label = heappop(maxHeap) value = -value #when you can't use that value if label in labelFrequencies and labelFrequencies[label] >= use_limit: continue if label not in labelFrequencies: labelFrequencies[label] = 0 labelFrequencies[label] += 1 numChosen += 1 maxSum += value return maxSum
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: # Greedy search # 1. sorted each item based on used frequency # 2. loop through and items until bag full items = sorted(list(zip(values, labels)), key=lambda x: -x[0]) res = 0 freq = defaultdict(int) n = 0 for i, (val, label) in enumerate(items): if freq[label] < use_limit: freq[label] += 1 res += val n += 1 if n == num_wanted: break return res
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
from collections import defaultdict class Solution: def quickselect(self, nums, K): def swap(nums, i, j): nums[i], nums[j] = nums[j], nums[i] def partition(nums, left, right, pivotIdx): if right-left <= 1: return left pivot = nums[pivotIdx] swap(nums, pivotIdx, right-1) read_idx = left write_idx = left while read_idx < right-1: if nums[read_idx] > pivot: swap(nums, read_idx, write_idx) write_idx += 1 read_idx += 1 swap(nums, write_idx, right-1) return write_idx left = 0 right = len(nums) pivotIdx = -1 while pivotIdx != K: pivotIdx = left + (right-left)//2 pivotIdx = partition(nums, left, right, pivotIdx) if pivotIdx < K: left = pivotIdx+1 elif pivotIdx > K: right = pivotIdx def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: valuesByLabel = defaultdict(list) for value, label in zip(values, labels): valuesByLabel[label].append(value) valuesWithinLimit = [] for i_label, i_values in valuesByLabel.items(): self.quickselect(i_values, use_limit) valuesWithinLimit += i_values[:use_limit] self.quickselect(valuesWithinLimit, num_wanted) return sum(valuesWithinLimit[:num_wanted])
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: dic = {} for i,j in zip(values,labels): if j not in dic: dic[j] = [i] else: dic[j].append(i) res_arr = [] for i in dic: res_arr.extend(sorted(dic[i],reverse=True)[0:use_limit]) res_arr.sort() count = 0 res = 0 while count < num_wanted and len(res_arr) > 0: tmp = res_arr.pop() res += tmp count += 1 return res
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: res = 0 arr = sorted(list(zip(values, labels)), key=lambda x: x[0], reverse=1) cnt_label = {} cnt_tot = 0 for val, lab in arr: if cnt_tot < num_wanted and cnt_label.get(lab, 0) < use_limit: cnt_tot += 1 cnt_label[lab] = cnt_label.get(lab, 0) + 1 res += val return res
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: d =defaultdict(list) n = len(labels) for i in range(n): d[labels[i]].append(values[i]) arr = [] for k,v in list(d.items()): d[k].sort(reverse=True) d[k] = d[k][:use_limit] arr.extend(d[k]) arr.sort(reverse=True) return sum(arr[:num_wanted])
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: heap = [] for v, l in zip(values, labels): heapq.heappush(heap, (-v, l)) count = collections.Counter() res = [] while heap and len(res) < num_wanted: v, l = heapq.heappop(heap) if count[l] < use_limit: res.append(v) count[l] += 1 return -sum(res)
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
from collections import defaultdict class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: if len(values) == 0: return 0 if len(values) != len(labels): raise ValueError sorted_value_labels = sorted(zip(values, labels), key=lambda x: -x[0]) label_counter = defaultdict(lambda: 0) i = 0 total = 0 S = 0 while S != num_wanted and i < len(values): val, label = sorted_value_labels[i] if label_counter[label] < use_limit: total += val label_counter[label] += 1 S += 1 i += 1 return total
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: sum = 0 ct = {} import numpy as np sorted_idx = np.argsort(-np.array(values)) select_ct = 0 for v in sorted_idx: print(v) if select_ct == num_wanted: break label = labels[v] if label not in list(ct.keys()): ct[label] = 1 sum += values[v] select_ct += 1 elif ct[label] < use_limit: ct[label] += 1 sum += values[v] select_ct += 1 else: continue print(sum) return sum
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: newList = [(v, l) for v, l in zip(values, labels)] newList.sort(reverse = True) ans = 0 i = 0 labelCounter = defaultdict(int) for v, l in newList: if labelCounter[l] < use_limit: # print(v, l) ans += v i += 1 labelCounter[l] += 1 if i == num_wanted: break return ans
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
from collections import defaultdict class Solution: def largestValsFromLabels(self, values, labels, num_wanted, use_limit): if not values or not labels: return 0 index = [i for i in range(len(values))] index.sort(key=lambda i: values[i], reverse=True) res = 0 lab_to_count = defaultdict(int) for i in index: if num_wanted == 0: return res l = labels[i] v = values[i] if l not in lab_to_count or lab_to_count[l] < use_limit: res += v lab_to_count[l] += 1 num_wanted -= 1 return res
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: all_value_labels = [(value, label) for value, label in zip(values, labels)] all_value_labels.sort(reverse=True) used = Counter() ans = [] for value, label in all_value_labels: if used[label] + 1 <= use_limit: used[label] += 1 ans.append(value) if len(ans) == num_wanted: break return sum(ans)
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: heap = [] for i in range(len(values)): heappush(heap, (-values[i], labels[i])) selected, label_counts = [], {} while len(selected) < num_wanted and heap: value, label = heappop(heap) if (cur_num := label_counts.get(label, 0)) < use_limit: label_counts[label] = cur_num + 1 selected.append(value) print(selected) return -sum(selected)
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: counts = collections.defaultdict(int) vl = sorted(zip(values,labels)) ans = 0 while num_wanted and vl: val,lab = vl.pop() if counts[lab] < use_limit: ans += val counts[lab] += 1 num_wanted -= 1 return ans
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
from collections import defaultdict class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: counts = defaultdict(int) s = 0 total_count = 0 inds = sorted(list(range(len(values))), key=lambda x: values[x], reverse=True) sorted_values = [values[idx] for idx in inds] sorted_labels = [labels[idx] for idx in inds] for i, val in enumerate(sorted_values): label = sorted_labels[i] if total_count < num_wanted and counts[label] < use_limit: counts[label] += 1 total_count += 1 s += val if total_count == num_wanted: break return s
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: vls = sorted(zip(values, labels), reverse=True) l2v = defaultdict(list) for v,l in vls: l2v[l].append(v) chosen = [] l_use = defaultdict(int) for i, (v, l) in enumerate(vls): if l_use[l] < use_limit: chosen.append((v,l)) l_use[l] += 1 if len(chosen) >= num_wanted: break # print(chosen) return sum(v for v,l in chosen)
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
from collections import Counter import heapq class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: h = list(zip([-v for v in values], labels)) heapq.heapify(h) counter = Counter() ans = 0 while num_wanted and h: heap_item = heapq.heappop(h) val, label = heap_item if counter[label] == use_limit: continue counter[label] += 1 ans += -val num_wanted -= 1 return ans
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: items = [] for i in range(len(values)): items.append((values[i], labels[i])) items.sort(key = lambda item: item[0], reverse=True) dic = Counter(labels) for item in dic: if dic[item] > use_limit: dic[item] = use_limit largest = 0 print(dic) print(items) for num in items: if num_wanted == 0: break current_label = num[1] value = num[0] print(current_label) if dic[current_label] > 0: num_wanted -= 1 dic[current_label] -= 1 largest += value return largest
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
from queue import PriorityQueue class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: pq = PriorityQueue() for i in range(len(values)): pq.put((-values[i],labels[i])) subset_sum = 0 ecount = 0 label_usage_count_map = {} while (pq.qsize()>0): popped_element = pq.get() v = -popped_element[0] l = popped_element[1] if (v<0): break if (ecount>=num_wanted): break lusage = label_usage_count_map.get(l,0) if (lusage>=use_limit): continue ecount += 1 subset_sum += v label_usage_count_map[l] = label_usage_count_map.get(l,0) + 1 return subset_sum
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: empty = {i : use_limit for i in set(labels)} ans = 0 pairs = [(values[i], labels[i]) for i in range(len(values))] pairs.sort(key = lambda x : (-x[0])) for index, pair in enumerate(pairs): if empty[pair[1]] > 0 and num_wanted > 0: ans += pair[0] empty[pair[1]] -= 1 num_wanted -= 1 return ans
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: val_label_tuple = [(-1*val, lab) for val, lab in zip(values, labels)] import heapq heapq.heapify(val_label_tuple) #maximum val is at the top counts = collections.defaultdict(int) ans = 0 while val_label_tuple: val, lab = heapq.heappop(val_label_tuple) if counts.get(lab, 0) < use_limit: ans += abs(val) num_wanted -= 1 if num_wanted == 0: break counts[lab] += 1 return ans ''' val_label_tuple = [(val, lab) for val, lab in zip(values, labels)] val_label_tuple = sorted(val_label_tuple, key=lambda x: x[0], reverse=True) count_items = defaultdict(int) ret_value = 0 for val, label in val_label_tuple: if count_items.get(label, 0) < use_limit: ret_value += val count_items[label] += 1 num_wanted -= 1 if num_wanted == 0: break return ret_value '''
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
from collections import defaultdict from queue import PriorityQueue class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: q = PriorityQueue() for i in range(len(values)): q.put((-values[i], values[i], labels[i])) d = defaultdict(lambda: 0) ans = [] while len(ans) < num_wanted and not q.empty(): _, n, l = q.get() if d[l] < use_limit: ans.append(n) d[l] += 1 return sum(ans)
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: values_w_labels = [(values[i], labels[i]) for i in range(len(values))] values_w_labels.sort(reverse=True) label_count = {} total = 0 count = 0 for value, label in values_w_labels: if label not in label_count: label_count[label] = 0 if label_count[label] < use_limit: total += value label_count[label] += 1 count += 1 if count == num_wanted: break return total
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
from heapq import * class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: maxHeap = [] maxSum = 0 for i in range(len(values)): heappush(maxHeap, (-values[i], labels[i])) usedLabels = defaultdict(int) while num_wanted > 0 and len(maxHeap) > 0: currVal, currLabel = heappop(maxHeap) if usedLabels[currLabel] < use_limit: usedLabels[currLabel] += 1 maxSum -= currVal num_wanted -= 1 return maxSum
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: hashmap = collections.defaultdict(int) maxHeap = [(-v,labels[i]) for i,v in enumerate(values)] heapq.heapify(maxHeap) out = 0 while num_wanted>0: if len(maxHeap)==0: break value, label = heapq.heappop(maxHeap) if hashmap[label]<use_limit: hashmap[label] = hashmap[label] +1 num_wanted -= 1 out = out - value return out
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: heap = [] for i in range(len(values)): heappush(heap, (-values[i], labels[i])) if use_limit == 0 or num_wanted == 0: return 0 used = {} ret = 0 while len(heap) > 0: heap_item = heappop(heap) value = heap_item[0] label = heap_item[1] used[label] = used.get(label, 0) + 1 if used[label] <= use_limit: ret += (-value) num_wanted -= 1 if num_wanted == 0: break return ret
We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S.   Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth item. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third item. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1 Output: 16 Explanation: The subset chosen is the first and fourth item. Example 4: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2 Output: 24 Explanation: The subset chosen is the first, second, and fourth item.   Note: 1 <= values.length == labels.length <= 20000 0 <= values[i], labels[i] <= 20000 1 <= num_wanted, use_limit <= values.length
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: from heapq import heapify, heappop from collections import Counter counter = Counter() pq, ans = [[-value, label] for value, label in zip(values, labels)], [] heapify(pq) while pq: cur = heappop(pq) if counter[cur[1]] < use_limit: counter[cur[1]] += 1 ans.append(-cur[0]) if len(ans) == num_wanted: break return sum(ans)
Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. Example 2: Input: "cccaaa" Output: "cccaaa" Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. Note that "cacaca" is incorrect, as the same characters must be together. Example 3: Input: "Aabb" Output: "bbAa" Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect. Note that 'A' and 'a' are treated as two different characters.
class Solution: def frequencySort(self, s): """ :type s: str :rtype: str """ counter = collections.Counter(s) colls = sorted(counter.items(), key=lambda k: k[1], reverse=True) res = '' for k, v in colls: res += k * v return res
Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. Example 2: Input: "cccaaa" Output: "cccaaa" Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. Note that "cacaca" is incorrect, as the same characters must be together. Example 3: Input: "Aabb" Output: "bbAa" Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect. Note that 'A' and 'a' are treated as two different characters.
class Solution: def frequencySort(self, s): """ :type s: str :rtype: str """ counter = {} for c in s: if c in counter: counter[c] += 1 else: counter[c] = 1 res = "" while counter: m = max(counter, key=counter.get) res += m * counter[m] del counter[m] return res
Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. Example 2: Input: "cccaaa" Output: "cccaaa" Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. Note that "cacaca" is incorrect, as the same characters must be together. Example 3: Input: "Aabb" Output: "bbAa" Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect. Note that 'A' and 'a' are treated as two different characters.
class Solution: def frequencySort(self, s): """ :type s: str :rtype: str """ ''' cnt = collections.Counter(s) tmp = list(k*v for k, v in cnt.items()) res = sorted(tmp, key=len, reverse=True) return ''.join(res) ''' res = '' cnt = collections.Counter(s) tmps = cnt.most_common() for tmp in tmps: res += tmp[0]*tmp[1] return res
Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. Example 2: Input: "cccaaa" Output: "cccaaa" Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. Note that "cacaca" is incorrect, as the same characters must be together. Example 3: Input: "Aabb" Output: "bbAa" Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect. Note that 'A' and 'a' are treated as two different characters.
class Solution: def frequencySort(self, s): """ :type s: str :rtype: str """ mapping = {} for c in s: mapping[c] = mapping[c] + 1 if c in mapping else 1 bucket = [[] for _ in range(len(s) + 1)] for c, freq in mapping.items(): bucket[freq].append(c) res = "" for i in range(len(s), -1, -1): for c in bucket[i]: for _ in range(i): res += c return res
Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. Example 2: Input: "cccaaa" Output: "cccaaa" Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. Note that "cacaca" is incorrect, as the same characters must be together. Example 3: Input: "Aabb" Output: "bbAa" Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect. Note that 'A' and 'a' are treated as two different characters.
class Solution: def frequencySort(self, s): """ :type s: str :rtype: str """ counter = collections.Counter(s) ret = "" for char, freq in counter.most_common(): ret += char * freq return ret
Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. Example 2: Input: "cccaaa" Output: "cccaaa" Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. Note that "cacaca" is incorrect, as the same characters must be together. Example 3: Input: "Aabb" Output: "bbAa" Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect. Note that 'A' and 'a' are treated as two different characters.
class Solution: def frequencySort(self, s): """ :type s: str :rtype: str """ charToFreq = {} freqToChar = {} for c in s: if c not in charToFreq: charToFreq[c] = 0 charToFreq[c] += 1 print(charToFreq) for key, value in list(charToFreq.items()): if value not in freqToChar: freqToChar[value] = [] freqToChar[value].append(key) print(freqToChar) result = [] for key in sorted(freqToChar, reverse = True): for char in freqToChar[key]: result += [char] * key return "".join(result)
Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. Example 2: Input: "cccaaa" Output: "cccaaa" Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. Note that "cacaca" is incorrect, as the same characters must be together. Example 3: Input: "Aabb" Output: "bbAa" Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect. Note that 'A' and 'a' are treated as two different characters.
class Solution: def frequencySort(self, s): """ :type s: str :rtype: str """ charToFreq = {} freqToChar = {} for c in s: if c not in charToFreq: charToFreq[c] = 0 charToFreq[c] += 1 for key, value in list(charToFreq.items()): if value not in freqToChar: freqToChar[value] = [] freqToChar[value].append(key) result = [] for key in range(len(s), -1, -1): if key in freqToChar: for char in freqToChar[key]: result += [char] * key return "".join(result)
Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. Example 2: Input: "cccaaa" Output: "cccaaa" Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. Note that "cacaca" is incorrect, as the same characters must be together. Example 3: Input: "Aabb" Output: "bbAa" Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect. Note that 'A' and 'a' are treated as two different characters.
class Solution: def frequencySort(self, s): """ :type s: str :rtype: str """ # using bucket bucket = [None] * (len(s)+1) hash_table = {} result = '' for item in s: hash_table[item] = hash_table.get(item,0)+1 for key,value in hash_table.items(): if bucket[value]: bucket[value].append((key,value)) else: bucket[value] = [(key,value)] for i in range(len(bucket)-1,-1,-1): if bucket[i]: for item in bucket[i]: result += item[0] * item[1] return result
Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. Example 2: Input: "cccaaa" Output: "cccaaa" Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. Note that "cacaca" is incorrect, as the same characters must be together. Example 3: Input: "Aabb" Output: "bbAa" Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect. Note that 'A' and 'a' are treated as two different characters.
class Solution: def frequencySort(self, s): """ :type s: str :rtype: str """ from collections import defaultdict from operator import itemgetter result = [] letter_to_feq = defaultdict(lambda:0) feq_to_letter = defaultdict(list) for c in s: letter_to_feq[c] += 1 max_count = -1 for k, v in letter_to_feq.items(): feq_to_letter[v].append(k) if v > max_count: max_count = v for i in range(max_count, 0, -1): if i in feq_to_letter: for c in feq_to_letter[i]: result = result + [c] * i return ''.join(result) '''hashmap = defaultdict(lambda: 0) for c in s: hashmap[c] += 1 for k, v in sorted(hashmap.items(), key=itemgetter(1), reverse=True): result = result + [k] * v return ''.join(result)'''
On an infinite plane, a robot initially stands at (0, 0) and faces north.  The robot can receive one of three instructions: "G": go straight 1 unit; "L": turn 90 degrees to the left; "R": turn 90 degress to the right. The robot performs the instructions given in order, and repeats them forever. Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.   Example 1: Input: "GGLLGG" Output: true Explanation: The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0). When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin. Example 2: Input: "GG" Output: false Explanation: The robot moves north indefinitely. Example 3: Input: "GL" Output: true Explanation: The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...   Note: 1 <= instructions.length <= 100 instructions[i] is in {'G', 'L', 'R'}
class Solution: def move(self, pos, direction): x, y = pos if direction == 0: y += 1 elif direction == 1: x += 1 elif direction == 2: y -= 1 elif direction == 3: x -= 1 return (x, y) def isRobotBounded(self, instructions: str) -> bool: direction = 0 # 0 for north, 1 for east, 2 for south, 3 for west pos = (0, 0) for i in instructions: if i == 'G': pos = self.move(pos, direction) elif i == 'L': direction = (direction - 1) % 4 elif i == 'R': direction = (direction + 1) % 4 if pos == (0, 0) or direction != 0: return True else: return False
On an infinite plane, a robot initially stands at (0, 0) and faces north.  The robot can receive one of three instructions: "G": go straight 1 unit; "L": turn 90 degrees to the left; "R": turn 90 degress to the right. The robot performs the instructions given in order, and repeats them forever. Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.   Example 1: Input: "GGLLGG" Output: true Explanation: The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0). When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin. Example 2: Input: "GG" Output: false Explanation: The robot moves north indefinitely. Example 3: Input: "GL" Output: true Explanation: The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...   Note: 1 <= instructions.length <= 100 instructions[i] is in {'G', 'L', 'R'}
class Solution: def isRobotBounded(self, instructions: str) -> bool: mapping = {0: [1, 0], 1: [0, 1], 2: [-1, 0], 3: [0, -1]} direction = 0 current = [0, 0] for instr in instructions: if instr == 'L': direction -= 1 elif instr == 'R': direction += 1 elif instr == 'G': move = mapping[direction] current[0] += move[0] current[1] += move[1] direction %= 4 if current == [0, 0] or direction != 0: return True return False
On an infinite plane, a robot initially stands at (0, 0) and faces north.  The robot can receive one of three instructions: "G": go straight 1 unit; "L": turn 90 degrees to the left; "R": turn 90 degress to the right. The robot performs the instructions given in order, and repeats them forever. Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.   Example 1: Input: "GGLLGG" Output: true Explanation: The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0). When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin. Example 2: Input: "GG" Output: false Explanation: The robot moves north indefinitely. Example 3: Input: "GL" Output: true Explanation: The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...   Note: 1 <= instructions.length <= 100 instructions[i] is in {'G', 'L', 'R'}
class Solution: def isRobotBounded(self, instructions: str) -> bool: x, y, dx, dy = 0, 0, 0, 1 for i in instructions: if i == 'R': dx, dy = dy, -dx if i == 'L': dx, dy = -dy, dx if i == 'G': x, y = x + dx, y + dy return (x, y) == (0, 0) or (dx, dy) != (0,1)
On an infinite plane, a robot initially stands at (0, 0) and faces north.  The robot can receive one of three instructions: "G": go straight 1 unit; "L": turn 90 degrees to the left; "R": turn 90 degress to the right. The robot performs the instructions given in order, and repeats them forever. Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.   Example 1: Input: "GGLLGG" Output: true Explanation: The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0). When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin. Example 2: Input: "GG" Output: false Explanation: The robot moves north indefinitely. Example 3: Input: "GL" Output: true Explanation: The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...   Note: 1 <= instructions.length <= 100 instructions[i] is in {'G', 'L', 'R'}
class Solution: def isRobotBounded(self, instructions: str) -> bool: # loop through all the commands in the arr # scenario the direction is not facing the same def is_infinite_loop(command): # iterate over all the commands # direction 0: NameError # x and y coordinates, if x and 0 is (0, 0) return True direction = [(0, 1), (1, 0), (0, -1), (-1, 0)] d_index = 0 x, y = 0, 0 for move in command: if move == 'G': x += direction[d_index][0] y += direction[d_index][1] elif move == 'R': d_index = (d_index + 1) % 4 elif move == 'L': d_index = (d_index + 3) % 4 # if back at origin # print(d_index) if x == y == 0: return True if (x != 0 or y != 0) and d_index != 0: return True return False return is_infinite_loop(instructions) # class Solution: # def isRobotBounded(self, instructions: str) -> bool: # L_occurances = instructions.count('L') # R_occurances = instructions.count('R') # difference = L_occurances - R_occurances # if difference % 4 == 0: # # check if loop otherwise return False too # directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # N, E, S, W # d = 0 # start at North index # point = [0, 0] # for instruction in instructions: # if instruction == 'G': # point[0] += directions[d][0] # point[1] += directions[d][1] # elif instruction == 'L': # d = (d + 3) % 4 # elif instruction == 'R': # d = (d + 1) % 4 # return True if point == [0, 0] else False # else: # return True # # return True if L_occurances - R_occurances != 0 else False
On an infinite plane, a robot initially stands at (0, 0) and faces north.  The robot can receive one of three instructions: "G": go straight 1 unit; "L": turn 90 degrees to the left; "R": turn 90 degress to the right. The robot performs the instructions given in order, and repeats them forever. Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.   Example 1: Input: "GGLLGG" Output: true Explanation: The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0). When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin. Example 2: Input: "GG" Output: false Explanation: The robot moves north indefinitely. Example 3: Input: "GL" Output: true Explanation: The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...   Note: 1 <= instructions.length <= 100 instructions[i] is in {'G', 'L', 'R'}
class Solution: def isRobotBounded(self, instructions: str) -> bool: move = {'N':(0,1), 'S':(0,-1), 'E':(1,0), 'W':(-1,0)} right = {'N':'E', 'S':'W', 'E':'S', 'W':'N'} left = {'N':'W', 'S':'E', 'E':'N', 'W':'S'} pos = (0,0) dire = 'N' for c in instructions: if c=='G': x, y = pos dx, dy = move[dire] pos = (x+dx, y+dy) elif c=='L': dire = left[dire] else: dire = right[dire] return pos==(0,0) or dire!='N'
On an infinite plane, a robot initially stands at (0, 0) and faces north.  The robot can receive one of three instructions: "G": go straight 1 unit; "L": turn 90 degrees to the left; "R": turn 90 degress to the right. The robot performs the instructions given in order, and repeats them forever. Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.   Example 1: Input: "GGLLGG" Output: true Explanation: The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0). When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin. Example 2: Input: "GG" Output: false Explanation: The robot moves north indefinitely. Example 3: Input: "GL" Output: true Explanation: The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...   Note: 1 <= instructions.length <= 100 instructions[i] is in {'G', 'L', 'R'}
class Solution: def isRobotBounded(self, instructions: str) -> bool: move = {'N':(0,1), 'S':(0,-1), 'E':(1,0), 'W':(-1,0)} right = {'N':'E', 'S':'W', 'E':'S', 'W':'N'} left = {'N':'W', 'S':'E', 'E':'N', 'W':'S'} pos = (0,0) dire = 'N' i=0 while i<4: for c in instructions: if c=='G': x, y = pos dx, dy = move[dire] pos = (x+dx, y+dy) elif c=='L': dire = left[dire] else: dire = right[dire] if pos==(0,0) and dire=='N': return True i+=1 return False
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
class Solution: def isvalid(self,C): if len(C)>2: return False if len(C)==1: a = min(C) if a==1 or C[a]==1: # EXPLANATION: # a==1 : All lengths are unitary like A=[1,2,3,4,...], so poping anything is fine # C[a]==1: We have a unique length occurence like A=[4,4,4,4,...], so poping anything is fine too return True # EXPLANATION: # For all other cases of len(C)==1, we'd end with a mistmatch like [1,1,2,2,2], or [1,1,1], so we need to \"return False\" right away return False # # --------- len(D)==2 -------------- # a,b = sorted(C) # -> Attempt removing from \"a\" if a==C[a]==1: # EXPLANATION: # If we remove from a chain of length \"a\", we will create something smaller than \"b\", so... # The only way to be fine is to have a single element, like [1,2,2,2,3,3,3,...] # -> If we had anything else, we would be stuck with a contradiction (so we move forward to removing \"b\") return True # -> Attempt removing from \"b\" # EXPLANATION: # This only works if there is a single chain of length \"b\", and poping one element makes a chain of length \"a\". # In other words, if works when \"C[b]==1 and (b-1)==a\" return True if ( C[b]==1 and (b-1)==a ) else False def remove(self,B,x): if B[x]==1: B.pop(x) else: B[x] -= 1 def maxEqualFreq(self, A): remove = self.remove B = Counter(A) # Count number of repetitions/length (per value) [1,1,2,2,3,3,4] = {1:2, 2:2, 3:2, 4:1} C = Counter(B.values()) # Count number of times a length has been seen [1,1,2,2,3,3,4] = { 1:1, 2:3 } # # -> Iterate Reversed, to get best answer at the first match for i in reversed(range(len(A))): # -> Check if C_dictionary is a valid answer if self.isvalid(C): return i+1 # # -> Remove current element \"x\" from our System x = A[i] # B[x] = N_repetitions for \"x\" # remove(C,B[x]) # Deregister old N_repetitions remove(B, x ) # Deregister one instance of \"x\" (from N_repetitions) if B[x]: # -> If N_repetitions>0 exists, register shortened length C[B[x]] += 1 return 0
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
class Solution: def maxEqualFreq(self, A: List[int]) -> int: n = len(A) count = collections.defaultdict(int) freq = collections.defaultdict(int) for i in range(n): count[A[i]] +=1 freq[count[A[i]]]+=1 for i in range(n-1, 0, -1): # If include A[i] if count[A[i]] * freq[count[A[i]]] == i: return i + 1 freq[count[A[i]]] -= 1 count[A[i]] -= 1 if count[A[i-1]] * freq[count[A[i-1]]] == i: return i + 1 return 1
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
class Solution: def maxEqualFreq(self, nums: List[int]) -> int: count = collections.defaultdict(int) freq = collections.defaultdict(int) for n in nums: count[n] += 1 freq[count[n]] += 1 for i in range(len(nums)-1, 0, -1): # 2 case, case 1 , keep i, then you have to remove another on from 0 -- i-1 if count[nums[i]] * freq[count[nums[i]]] == i: return i+1 freq[count[nums[i]]] -= 1 count[nums[i]] -= 1 if count[nums[i-1]] * freq[count[nums[i-1]]] == i: return i+1 return 1
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
class Solution: def maxEqualFreq(self, nums: List[int]) -> int: counts = collections.defaultdict(int) freq = collections.defaultdict(int) res = 0 for i in range(len(nums)): counts[nums[i]] += 1 freq[counts[nums[i]]] += 1 count = counts[nums[i]] * freq[counts[nums[i]]] if count == i + 1 and i != len(nums) - 1: res = max(res,i + 2) if count == i: res = max(res,i + 1) return res
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
class Solution: def maxEqualFreq(self, nums: List[int]) -> int: counts = collections.defaultdict(int) freq = collections.defaultdict(int) res = 0 for i in range(len(nums)): counts[nums[i]] += 1 freq[counts[nums[i]]] += 1 count = counts[nums[i]] * freq[counts[nums[i]]] if count == i + 1 and i != len(nums) - 1: res = max(res,i + 2) if count == i: res = max(res,i + 1) return res
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
class Solution: def maxEqualFreq(self, nums: List[int]) -> int: counts = collections.defaultdict(int) freq = collections.defaultdict(int) res = 0 for i in range(len(nums)): counts[nums[i]] += 1 freq[counts[nums[i]]] += 1 count = counts[nums[i]] * freq[counts[nums[i]]] if count == i + 1 and i != len(nums) - 1: res = max(res,i + 2) if count == i: res = max(res,i + 1) return res
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
class Solution: def maxEqualFreq(self, nums: List[int]) -> int: counts = collections.defaultdict(int) freq = collections.defaultdict(int) res = 0 for i in range(len(nums)): counts[nums[i]] += 1 freq[counts[nums[i]]] += 1 count = counts[nums[i]] * freq[counts[nums[i]]] if count == i + 1 and i != len(nums) - 1: res = max(res,i + 2) elif count == i: res = max(res,i + 1) return res
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
from collections import Counter, defaultdict class Solution: def maxEqualFreq(self, nums: List[int]) -> int: counter = Counter(nums) # d: count -> values has such counts d = defaultdict(set) for x in counter: d[counter[x]].add(x) # O(n), reverse go through nums updating count of counts i = len(nums) while d: if len(d) == 1: k = list(d.keys())[0] if k == 1 or len(d[k]) == 1: return i if len(d) == 2: y, z = sorted(d.keys()) if (y == 1 and len(d[y]) == 1) or (y + 1 == z and len(d[z]) == 1): return i i -= 1 # update counter and count of counts x = nums[i] d[counter[x]].remove(x) if not d[counter[x]]: d.pop(counter[x]) counter[x] -= 1 if counter[x] > 0: d[counter[x]].add(x) return 0
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
from collections import Counter, defaultdict class Solution: def maxEqualFreq(self, nums: List[int]) -> int: counter = Counter(nums) # d: count -> values has such counts d = defaultdict(set) for x in counter: d[counter[x]].add(x) # O(n), reverse go through nums updating count of counts n = len(nums) while d: if len(d) == 1: k = list(d.keys())[0] if k == 1 or len(d[k]) == 1: return n if len(d) == 2: y, z = sorted(d.keys()) if (y == 1 and len(d[y]) == 1) or (y + 1 == z and len(d[z]) == 1): return n n -= 1 # update counter and count of counts x = nums[n] d[counter[x]].remove(x) if not d[counter[x]]: d.pop(counter[x]) counter[x] -= 1 if counter[x] > 0: d[counter[x]].add(x) return 0
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
class Solution: def maxEqualFreq(self, nums: List[int]) -> int: num_freq = {} freq_freq = {} for num in nums: num_freq[num] = num_freq.get(num, 0) + 1 for f in num_freq.values(): freq_freq[f] = freq_freq.get(f, 0) + 1 n = len(nums) if len(freq_freq) == 2: key1, key2 = list(freq_freq.keys()) if freq_freq[key1] == 1 and (key1 == 1 or key1 == key2 + 1): return n if freq_freq[key2] == 1 and (key2 == 1 or key2 == key1 + 1): return n if len(freq_freq) == 1: key = list(freq_freq.keys())[0] if key == 1 or freq_freq[key] == 1: return n for i in range(n): num = nums[n - i - 1] prev_freq = num_freq[num] num_freq[num] -= 1 freq_freq[prev_freq] -= 1 if freq_freq[prev_freq] == 0: del freq_freq[prev_freq] if num_freq[num] != 0: freq_freq[num_freq[num]] = freq_freq.get(num_freq[num], 0) + 1 if len(freq_freq) == 2: key1, key2 = list(freq_freq.keys()) if freq_freq[key1] == 1 and (key1 == 1 or key1 == key2 + 1): return n - i - 1 if freq_freq[key2] == 1 and (key2 == 1 or key2 == key1 + 1): return n - i - 1 if len(freq_freq) == 1: key = list(freq_freq.keys())[0] if key == 1 or freq_freq[key] == 1: return n - i - 1 return 0
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
from collections import defaultdict class Solution: def maxEqualFreq(self, nums: List[int]) -> int: if not nums: return 0 ans = 0 max_f = 0 counter, freq_counter = defaultdict(int), defaultdict(int) for idx, val in enumerate(nums): counter[val] += 1 max_f = max(max_f, counter[val]) freq_counter[counter[val]-1] -= 1 freq_counter[counter[val]] += 1 if max_f == 1 or max_f * freq_counter[max_f] == idx or ((max_f-1) * (freq_counter[max_f-1] + 1)) == idx: ans = max(ans, idx+1) return ans
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
class Solution: def maxEqualFreq(self, nums: List[int]) -> int: from collections import defaultdict freq = defaultdict(int) count = defaultdict(int) res = 0 for i, n in enumerate(nums, 1): freq[count[n]] -= 1 freq[count[n] + 1] += 1 count[n] += 1 if freq[count[n]] * count[n] == i and i < len(nums): res = i + 1 d = i - freq[count[n]] * count[n] if d in [1, count[n]+1] and freq[d] == 1: res = i return res
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
class Solution: def maxEqualFreq(self, nums: List[int]) -> int: counts = collections.Counter() freq = collections.Counter() res = 0 for i in range(len(nums)): counts[nums[i]] += 1 freq[counts[nums[i]]] += 1 count = counts[nums[i]] * freq[counts[nums[i]]] if count == i + 1 and i != len(nums) - 1: res = max(res,i + 2) elif count == i: res = max(res,i + 1) return res
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
class Solution: def maxEqualFreq(self, nums: List[int]) -> int: counts, freq = collections.Counter(), collections.Counter() res = 0 for i, num in enumerate(nums): counts[num] += 1 freq[counts[num]] += 1 count = freq[counts[num]] * counts[num] if count == i + 1 and i != len(nums) - 1: res = max(res, i + 2) elif count == i: res = max(res, i + 1) return res
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
class Solution: def maxEqualFreq(self, nums: List[int]) -> int: freq_count, count, res, maxf = defaultdict(int), defaultdict(int), 0, 0 for i, a in enumerate(nums): count[a] += 1 freq_count[count[a]-1] -= 1 freq_count[count[a]] += 1 maxf = max(maxf, count[a]) if maxf==1 or maxf*freq_count[maxf]+1==i+1 or (maxf-1)*freq_count[maxf-1]+maxf==i+1: res = i+1 return res
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
class Solution: def maxEqualFreq(self, nums: List[int]) -> int: count = collections.Counter() freq = [0 for _ in range(len(nums) + 1)] res = 0 for n, a in enumerate(nums, 1): freq[count[a]] -= 1 freq[count[a] + 1] += 1 c = count[a] = count[a] + 1 if freq[c] * c == n and n < len(nums): res = n + 1 d = n - freq[c] * c if d in [c + 1, 1] and freq[d] == 1: res = n return res
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
from collections import defaultdict class Solution: def maxEqualFreq(self, nums: List[int]) -> int: n = len(nums) elemfreq = defaultdict(int) freqcnt = defaultdict(int) i = 0 n_distinct = 0 maxfreq = 0 maxprefix = None while i != n: x = nums[i] if elemfreq[x] == 0: n_distinct += 1 elemfreq[x] += 1 freqcnt[1] += 1 else: freqcnt[elemfreq[x]] -= 1 freqcnt[elemfreq[x]+1] += 1 elemfreq[x] += 1 maxfreq = max(maxfreq, elemfreq[x]) if maxfreq == 1: maxprefix = i elif (freqcnt[1] == 1) and (freqcnt[maxfreq] == n_distinct-1): maxprefix = i elif (freqcnt[maxfreq] == 1) and (freqcnt[maxfreq-1] == n_distinct-1): maxprefix = i i += 1 return maxprefix+1
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
class Solution: def maxEqualFreq(self, nums) -> int: res = maxFrq = 0 count = defaultdict(int) freq = defaultdict(int) for i, num in enumerate(nums): cnt = count[num] freq[cnt] -= 1 cnt += 1 count[num] = cnt freq[cnt] += 1 maxFrq = max(maxFrq, cnt) if (maxFrq == 1) or (maxFrq*freq[maxFrq]) == i or ((maxFrq-1)*(freq[maxFrq-1] + 1)) == i: res = i + 1 return res
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
class Solution: def maxEqualFreq(self, nums: List[int]) -> int: countMap, freqMap, maxFreq, maxIndex = defaultdict(int), defaultdict(int), 0, 0 for index, x in enumerate(nums): freqMap[countMap[x]] -= 1 countMap[x] += 1 freqMap[countMap[x]] += 1 maxFreq = max(maxFreq, countMap[x]) if maxFreq*freqMap[maxFreq] == index or (maxFreq-1)*(freqMap[maxFreq-1]+1) == index or maxFreq == 1: maxIndex = index+1 return maxIndex
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
class Solution: def maxEqualFreq(self, A): count = collections.Counter() freq = [0 for _ in range(len(A) + 1)] res = 0 for n, a in enumerate(A, 1): freq[count[a]]-=1 freq[count[a]+1]+=1 c = count[a]=count[a]+1 if freq[c]*c==n and n<len(A): res = n+1 d = n-freq[c]*c if d in [c+1,1] and freq[d]==1: res = n return res
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
from collections import Counter class Solution: def maxEqualFreq(self, nums: List[int]) -> int: dic = Counter(nums) dicdic = Counter(list(dic.values())) if len(nums) == 2: return 2 while True: if len(dicdic) == 1 and (min(dicdic) == 1 or min(dicdic.values()) == 1): return len(nums) if len(dicdic) == 2: max_dicdic_keys = max(dicdic) min_dicdic_keys = min(dicdic) if max_dicdic_keys - min_dicdic_keys == 1 and dicdic[max_dicdic_keys] == 1: return len(nums) if min_dicdic_keys == 1 and dicdic[min_dicdic_keys] == 1: return len(nums) cleanup = nums.pop() if dic[cleanup] - 1 == 0: del dic[cleanup] else: dic[cleanup] = dic[cleanup] -1 dicdic = Counter(list(dic.values())) return
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
class Solution: def maxEqualFreq(self, nums) -> int: res = maxFrq = 0 count = defaultdict(int) freq = defaultdict(int) for i, num in enumerate(nums): cnt = count[num] freq[cnt] -= 1 count[num] += 1 freq[cnt+1] += 1 maxFrq = max(maxFrq, cnt+1) if (maxFrq == 1) or (maxFrq*freq[maxFrq]) == i or ((maxFrq-1)*(freq[maxFrq-1] + 1)) == i: res = i + 1 return res
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
class Solution: def maxEqualFreq(self, A): count = collections.Counter() freq = [0 for _ in range(len(A) + 1)] res = 0 for n, a in enumerate(A, 1): freq[count[a]] -= 1 freq[count[a] + 1] += 1 c = count[a] = count[a] + 1 if freq[c] * c == n and n < len(A): res = n + 1 d = n - freq[c] * c if d in [c + 1, 1] and freq[d] == 1: res = n return res
Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).   Example 1: Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice. Example 2: Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13 Example 3: Input: nums = [1,1,1,2,2,2] Output: 5 Example 4: Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8   Constraints: 2 <= nums.length <= 10^5 1 <= nums[i] <= 10^5
from collections import defaultdict class Solution: def maxEqualFreq(self, nums: List[int]) -> int: counter, freq = defaultdict(int), defaultdict(int) max_f = 0 ans = 0 for idx, num in enumerate(nums): counter[num] += 1 freq[counter[num]-1] -= 1 freq[counter[num]] += 1 max_f = max(max_f, counter[num]) if freq[max_f] * max_f == idx or max_f == 1 or (max_f-1)*(freq[max_f-1] + 1) == idx: ans = idx+1 return ans