question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
minimum-time-to-make-array-sum-at-most-x | Easy Iterative Solution | easy-iterative-solution-by-kvivekcodes-p6pc | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | kvivekcodes | NORMAL | 2024-09-04T12:20:28.107236+00:00 | 2024-09-04T12:20:28.107268+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minimumTime(vector<int>& nums1, vector<int>& nums2, int x) {\n int n = nums1.size();\n\n int sum = 0, sum2 = 0; \n for(auto it: nums1) sum += it;\n for(auto it: nums2) sum2 += it;\n if(sum <= x) return 0;\n if(n == 1) return 1;\n\n vector<pair<int, int> > v;\n for(int i = 0; i < n; i++){\n v.push_back({nums2[i], nums1[i]});\n }\n sort(v.begin(), v.end());\n\n vector<vector<long long> > dp(n+1, vector<long long> (n+1, -1e6));\n for(int i = 0; i <= n; i++){\n dp[i][0] = 0;\n }\n for(int i = 0; i <= n; i++) dp[0][i] = 0;\n for(long long i = 1; i <= n; i++){\n for(long long j = 1; j <= n; j++){\n dp[i][j] = max(dp[i-1][j], v[i-1].second + j * v[i-1].first + dp[i-1][j-1]);\n }\n }\n\n for(int i = 0; i <= n; i++){\n if(sum + sum2 * i - dp[n][i] <= x) return i;\n }\n\n return -1;\n }\n};\n``` | 0 | 0 | ['Array', 'Dynamic Programming', 'Sorting', 'C++'] | 0 |
minimum-time-to-make-array-sum-at-most-x | 20 Lines Simple Bottom Up DP | 20-lines-simple-bottom-up-dp-by-alex-e-x08d | Solution\nFor an optimal solution, if we have indices i1, i2... as a part of the optimal solution where we set the index to 0, then when doing the operation in | alex-e | NORMAL | 2024-08-04T21:35:54.716826+00:00 | 2024-08-04T21:37:22.251401+00:00 | 27 | false | # Solution\nFor an optimal solution, if we have indices i1, i2... as a part of the optimal solution where we set the index to 0, then when doing the operation in the problem, we should go in order of nums2[i1]<=nums2[i2]... because we want to pick the greatest value last and let the value accumulate before we set it to 0.\nThis is clearly DP since there are tons of cases and we have to make optimal decisions. Its not greedy because even though we go from the lowest nums2, we might not have to do an operation there. When picking which indices to set to 0, the total run time can be O(2^n). When thinking of how to structure DP, we may want to use 2D DP, but we then need to know the max amount of operations. \nTo help us get there, we should realize that for an optimal solution, we only have to set an index to 0 once. Proof: if we make the assumption that we have to do it twice, instead of doing it the first time, we could just do it the second time, and it would still go to 0, making it one less operation. Thus, we know the maximum number of operations is len(nums)\n\ndp[i][j] represents the minimum value after i operations after deleting nums[j\'] where j\' <= j . In other words, an optimal solution may never include deleting a number, and since we always delete in increasing order of j, if deleting nums2[j] is greater than a previous found number, then itll never be in the solution. \n\nThe transition fucntion is dp[i][j] = min(prev in dp[i], dp[i-1][j-1] - nums2[j] - i * nums1[j] + delta). In other words, subtract the accumulated numbers in that index, subtract the starting number, and then add delta.\n\n\n\n# Code\n```\nclass Solution:\n def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:\n dp = [[0] * (len(nums1)) for _ in range(len(nums1) + 1)]\n start, delta = sum(nums1), sum(nums2)\n if start <= x:\n return 0\n nums = [[n1, n2] for n1,n2 in zip (nums1, nums2)]\n dp[0] = [start] * (len(nums1))\n nums.sort(key = lambda s:(s[1], s[0]))\n\n for i in range(1,len(nums) + 1):\n minVal = float(\'inf\')\n for j in range(len(nums)):\n if i > j + 1:\n continue\n minVal = min(minVal, dp[i-1][j-1] - i * nums[j][1] - nums[j][0] + delta)\n dp[i][j] = minVal\n if dp[i][j] <= x:\n return i\n return -1\n \n``` | 0 | 0 | ['Dynamic Programming', 'Python3'] | 0 |
minimum-time-to-make-array-sum-at-most-x | As hinted | as-hinted-by-maxorgus-61ep | Note the dp should not be done with python builtin memoization which would cause MLE, in stead, do the tabulation yourself\n\n# Code\n\nclass Solution:\n def | MaxOrgus | NORMAL | 2024-05-14T02:52:38.130775+00:00 | 2024-05-14T02:52:38.130807+00:00 | 5 | false | Note the dp should not be done with python builtin memoization which would cause MLE, in stead, do the tabulation yourself\n\n# Code\n```\nclass Solution:\n def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:\n n = len(nums1)\n nums = [(n1,n2) for n1,n2 in zip(nums1,nums2)]\n nums.sort(key = lambda x:x[1])\n nowsum = sum([x[0] for x in nums])\n if nowsum <= x: return 0\n dp = [[0 for i in range(n+1)] for j in range(n)]\n for i in range(n):\n for t in range(n+1):\n if t == 0:\n dp[i][t] =0\n else:\n dp[i][t] = max(dp[i-1][t],dp[i-1][t-1] + nums[i][1]*t + nums[i][0])\n\n sA = sum(nums1)\n sB = sum(nums2)\n for t in range(n+1):\n if sA+sB*t -dp[n-1][t]<=x:\n return t\n return -1\n\n \n``` | 0 | 0 | ['Python3'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Space Efficient Solution ... | space-efficient-solution-by-gp_777-pxto | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | GP_777 | NORMAL | 2024-04-23T03:55:41.499004+00:00 | 2024-04-23T03:55:41.499038+00:00 | 7 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minimumTime(List<Integer> A, List<Integer> B, int x) {\n int n = A.size(), sa = 0, sb = 0, dp[] = new int[n + 1];\n List<List<Integer>> BA = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n int a = A.get(i), b = B.get(i);\n BA.add(Arrays.asList(b, a));\n sa += a;\n sb += b;\n }\n Collections.sort(BA, (o1, o2) -> Integer.compare(o1.get(0), o2.get(0)));\n for (int j = 0; j < n; ++j)\n for (int i = j + 1; i > 0; --i)\n dp[i] = Math.max(dp[i], dp[i - 1] + i * BA.get(j).get(0) + BA.get(j).get(1));\n for (int i = 0; i <= n; ++i)\n if (sb * i + sa - dp[i] <= x)\n return i;\n return -1;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Solution | solution-by-gp_777-d3gn | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | GP_777 | NORMAL | 2024-04-23T02:19:46.084231+00:00 | 2024-04-23T02:19:46.084251+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n\n public int minimumTime(List<Integer> nums1, List<Integer> nums2, int x) {\n \n final int[][] pairs = new int[nums1.size()][2];\n int sum1 = 0;\n int sum2 = 0;\n for (int i = 0; i < nums1.size(); ++i) {\n final int n1 = nums1.get(i);\n final int n2 = nums2.get(i);\n sum1 += n1;\n sum2 += n2;\n pairs[i][0] = n1;\n pairs[i][1] = n2;\n }\n \n Arrays.sort(pairs, (a, b) -> {\n int diff = Integer.compare(a[1], b[1]);\n if (diff == 0) {\n diff = Integer.compare(a[0], b[0]);\n }\n return diff;\n });\n final int n = pairs.length;\n \n final int[][] dp = new int[n + 1][n + 1];\n for (int i = 1; i <= n; ++i) {\n for (int j = 1; j <= i; ++j) {\n final int withoutIthPair = dp[i - 1][j]; \n final int withIthPair = dp[i - 1][j - 1] \n + (pairs[i - 1][1] * j) \n + pairs[i - 1][0]; \n dp[i][j] = Math.max(withoutIthPair, withIthPair);\n }\n }\n \n for (int t = 0; t <= n; ++t) {\n final int sum = sum1 + (sum2 * t) - dp[n][t];\n if (sum <= x) {\n return t;\n }\n }\n \n return -1;\n }\n\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Minimum Time to Process Arrays with Constraints Beats 81.20% | minimum-time-to-process-arrays-with-cons-949c | Intuition\nThe problem seems to involve finding the minimum time required to perform certain operations on two arrays while satisfying certain conditions. \n\n# | kumarritul089 | NORMAL | 2024-03-15T07:09:40.496951+00:00 | 2024-03-15T07:09:40.496980+00:00 | 29 | false | # Intuition\nThe problem seems to involve finding the minimum time required to perform certain operations on two arrays while satisfying certain conditions. \n\n# Approach\n1. We start by calculating the total sums of both arrays, `nums1` and `nums2`, and storing the indices in a separate vector.\n2. If the sum of `nums1` is less than or equal to `x`, then we can return 0 as no operations are needed.\n3. Otherwise, we sort the indices based on the values of `nums2`.\n4. We then utilize dynamic programming to find the minimum time. We iterate over the sorted indices and calculate the time taken for each possible number of elements from `nums2` to be processed, considering the time it takes to process elements from both arrays.\n5. We keep track of the minimum time found so far, updating it whenever we find a new minimum time that satisfies the given condition.\n6. Finally, we return the minimum time found or -1 if it\'s not possible to satisfy the condition.\n\n# Complexity\n- Time complexity:\n - Sorting the indices based on `nums2` takes O(n*log(n)) time.\n - The dynamic programming approach takes O(n^2) time.\n - Therefore, the overall time complexity is O(n^2).\n- Space complexity:\n - We use additional space for the `ind` vector and the `dp` vector, both of size `n`, resulting in a space complexity of O(n).\n\n# Code\n``` C++ []\nclass Solution {\npublic:\n int minimumTime(vector<int>& nums1, vector<int>& nums2, int x) {\n const int n = nums1.size();\n vector<int> ind(n);\n int s = 0, d = 0;\n for (int i = 0; i < n; ++i) {\n ind[i] = i;\n s += nums1[i];\n d += nums2[i];\n }\n if (s <= x) {\n return 0;\n }\n sort(ind.begin(), ind.end(), [&](const int a, const int b) {\n return nums2[a] < nums2[b];\n });\n vector<int> dp(n + 1);\n int r = n + 1;\n for (int i = 1; i <= n; ++i) {\n for (int j = min(i, r - 1); j; --j) {\n dp[j] = max(dp[j], dp[j - 1] + nums2[ind[i - 1]] * j + nums1[ind[i - 1]]);\n if (s + j * d - dp[j] <= x) {\n r = j;\n }\n }\n }\n return r <= n ? r : -1;\n }\n};\n```\n```javascript []\nfunction minimumTime(nums1, nums2, x) {\n const n = nums1.length;\n let ind = Array.from({ length: n }, (_, i) => i);\n let s = 0, d = 0;\n \n for (let i = 0; i < n; ++i) {\n s += nums1[i];\n d += nums2[i];\n }\n \n if (s <= x) {\n return 0;\n }\n \n ind.sort((a, b) => nums2[a] - nums2[b]);\n let dp = new Array(n + 1).fill(0);\n let r = n + 1;\n \n for (let i = 1; i <= n; ++i) {\n for (let j = Math.min(i, r - 1); j; --j) {\n dp[j] = Math.max(dp[j], dp[j - 1] + nums2[ind[i - 1]] * j + nums1[ind[i - 1]]);\n if (s + j * d - dp[j] <= x) {\n r = j;\n }\n }\n }\n \n return r <= n ? r : -1;\n}\n\n```\n```python []\nclass Solution:\n def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:\n n = len(nums1)\n ind = list(range(n))\n s, d = 0, 0\n for i in range(n):\n s += nums1[i]\n d += nums2[i]\n if s <= x:\n return 0\n\n # Custom comparator for sorting ind based on nums2 values\n ind.sort(key=lambda i: nums2[i])\n\n dp = [0] * (n + 1)\n r = n + 1\n for i in range(1, n + 1):\n for j in range(min(i, r - 1), 0, -1):\n dp[j] = max(dp[j], dp[j - 1] + nums2[ind[i - 1]] * j + nums1[ind[i - 1]])\n if s + j * d - dp[j] <= x:\n r = j\n return r if r <= n else -1\n```\n\n | 0 | 0 | ['Array', 'Dynamic Programming', 'Sorting', 'Python', 'C++', 'Python3', 'JavaScript'] | 0 |
minimum-time-to-make-array-sum-at-most-x | 5 hours, mega failure | 5-hours-mega-failure-by-user3043sb-ex8v | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | user3043SB | NORMAL | 2024-01-21T14:06:03.398487+00:00 | 2024-01-21T14:06:03.398517+00:00 | 1 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport java.util.*;\n\n\npublic class Solution {\n // sum2 - max(A2) > X => IMPOSSIBLE = -1\n // sum2 is CONSTANT !!!!\n\n // so we are looking for steps using i,j...\n // sum1 + (sum2 - A2[i] - A1[i]) + (sum2 - A2[j] - A1[j]) .... <= X\n // sum1 + numSteps * sum2 - (A2[i] + A1[i] + A2[j] + A1[j]...) <= X\n\n\n // Flipping an index sets it to 0 = MIN possible value\n // its best to let it accumulate and flip it ONCE at the end, make it 0; no point flipping it twice...\n // nums1 = [1000, 1] x = 900\n // nums2 = [900 ,1000]\n // 1st , 2nd\n\n // REALIZATION 1: NEVER FLIP TWICE !!!!!! so the problem becomes about WHICH INDEXES and WHICH ORDER !!!!!!!\n // REALIZATION 2: ORDER OF FLIPS: ALWAYS FLIP smallest gains A2[i] first !!!!!!! they are slower to accumulate\n // while we flip bigger ones later, allowing them to accumulate and kill them off immediately; OR NO FLIP AT ALL\n\n // IDEA: sort by the gain; then we have only 2 choices: flip or not !!!\n\n // initial DP approach: can be also iterative; works on the SUM as dimension; but the sum range is 0..1,000,000!!!\n\n // Convert the problem into something else to extract the sum OUT OF THE DP DIMENSIONS !!!!!\n // the other possible dimensions left are: INDEX and NUM_STEPS which go 0...N !!!! so: O(N^2)\n // redefine DP: dp[i][steps] = MIN sum possible using indexes 0..i and this num steps\n // NOTICE: when we flip A[i] totalSum INCREASES but prefixSum DECREASES !!!!\n // so do DP on the prefixSum !!!!\n\n\n public int minimumTime(List<Integer> nums1, List<Integer> nums2, int x) {\n this.n = nums1.size();\n this.x = x;\n this.A = new int[n][2];\n int minSteps = Integer.MAX_VALUE;\n for (int i = 0; i < n; i++) {\n sum1 += A[i][0] = nums1.get(i);\n sum2 += A[i][1] = nums2.get(i);\n }\n if (sum1 <= x) return 0;\n Arrays.sort(A, (a, b) -> Integer.compare(a[1], b[1])); // sort by gain\n\n int[] prefA1 = new int[n + 1]; // prefSum of A1\n int[] prefA2 = new int[n + 1]; // prefixSum of A2 = prefixGain\n for (int i = 1; i <= n; i++) {\n prefA1[i] = prefA1[i - 1] + A[i - 1][0];\n prefA2[i] = prefA2[i - 1] + A[i - 1][1];\n }\n int[][] dp = new int[n + 1][n + 1];\n for (int i = 1; i <= n; i++) {\n dp[i][0] = prefA1[i];\n for (int j = 1; j <= i; j++) { // stepsTaken\n int take = dp[i - 1][j - 1] + prefA2[i - 1]; // take; make A1[i] = 0\n int notTake = dp[i - 1][j] + A[i - 1][0] + j * A[i - 1][1]; // NOT take\n\n dp[i][j] = take;\n if (i > j) dp[i][j] = Math.min(dp[i][j], notTake);\n if (i == n && dp[i][j] <= x) minSteps = Math.min(minSteps, j);\n }\n }\n\n return minSteps == Integer.MAX_VALUE ? -1 : minSteps;\n// int res = recMemo(0, sum1, 0);\n// return res >= Integer.MAX_VALUE / 2 ? -1 : res;\n }\n\n // [9,10,4,4] x = 16\n // [1, 3,4,4]\n\n\n // initial DP approach: can be also iterative; works on the SUM as dimension; but the sum range is 0..1,000,000!!!\n // DIMENSION is TOO BIG !!!!!!!\n// int recMemo(int i, int sum, int stepsTaken) { // adding cache is too much memory; O(n*n*1 000 000)\n// if (sum <= x) return 0;\n// if (i == n) return Integer.MAX_VALUE / 2;\n//\n// int gainRest = sum2 - A[i][1];\n// int currVal = A[i][0] + stepsTaken * A[i][1];\n// int take = recMemo(i + 1, sum + gainRest - currVal, stepsTaken + 1);\n// int notTake = recMemo(i + 1, sum, stepsTaken);\n//\n// return Math.min(1 + take, notTake);\n// }\n\n int sum1, sum2, n, x;\n int[][] A;\n\n\n}\n\n\n``` | 0 | 0 | ['Java'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Alternative to DP, a Short, Straightforward O(N^2) Greedy Solution in Python | alternative-to-dp-a-short-straightforwar-4jv3 | Approach\n Describe your approach to solving the problem. \nThe best solution with a length of l is based on the best solution with the length of l-1 and an ite | metaphysicalist | NORMAL | 2023-12-26T19:27:38.514813+00:00 | 2023-12-26T21:57:29.250663+00:00 | 17 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nThe best solution with a length of `l` is based on the best solution with the length of `l-1` and an item that is not selected yet. \nThus, my solution builds the solution from length 1 to `n`, one by one. \nBased on the solution of `l-1`, my solution picks up the best item from the remaining set `r`. The criteria is easy that the addition of the new item makes the lowest score. By exploring each of the items in `r` with an $O(1)$ scoring function, the overal complexity is $O(N^2)$.\n\n\n# Complexity\n- Time complexity: $O(N^2)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(N)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:\n def cost(q, r, l):\n return sum((l-i-1) * b for i, (_, b) in enumerate(q)) \\\n + sum(a + l * b for a, b in r)\n q, r = [], sorted([(a, b) for a, b in zip(nums1, nums2)], key=lambda x: (x[1], x[0]))\n if cost(q, r, len(q)) <= x:\n return 0\n while r:\n prefix_sums = list(accumulate((b for _, b in q), initial=0))\n best_score, best_i, best_j = -inf, -1, -1\n j = 0\n for i, (a2, b2) in enumerate(r):\n while j < len(q) and q[j][1] < b2:\n j += 1\n if (score := a2 + b2 * (j+1) - prefix_sums[j]) > best_score:\n best_score, best_i, best_j = score, i, j\n q.insert(best_j, r.pop(best_i))\n if cost(q, r, len(q)) <= x:\n return len(q)\n return -1\n``` | 0 | 0 | ['Greedy', 'Python3'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Most intuitive & Easyy Top Down solution || recursion+memoizaton | most-intuitive-easyy-top-down-solution-r-i3ov | Idea & thoughts...\n\nwhat will happen after t days if we don\'t delete anything the \ns1: sum of a1\ns2: sum of a2\n\nsum will be = s1 + t*s2\nso now if we wan | demon_code | NORMAL | 2023-10-12T11:11:45.779308+00:00 | 2023-10-12T11:17:12.633698+00:00 | 26 | false | Idea & thoughts...\n\nwhat will happen after t days if we don\'t delete anything the \ns1: sum of a1\ns2: sum of a2\n\nsum will be = ```s1 + t*s2```\nso now if we want to delete some index i element at time p then \nsum will be = ```s1+t*s2 - a1[i]- p*a2[i] ```\nSo what we see here is the ```s1+ t*s2 ```remains constant for any t but ```a1[i]+p*a2[i] ```varies and we want to ```sum<=x ``` so we need to minimise the negative part :\nso it will be wise to delete every day some element bcz it will increase negative part, means have to select t elemets out of n\n\nthe maximum no of days can be n if we are not able to do so with in n it\'s not possible \n\nbcz let\'s say u removed some i element at ``` t ``` day ( which had value ``` a1[i]+t*a2[i] ``` at t day ) and after some time ``` p ``` it has become ``` p*a2[i] ``` and now u want to remove it again so it will be again zero but what\'s point of it u can simply delete it after t+p days and have same negative effects but after ``` t+p ```days it has more addition at other indexes so it doesn\'t helps to decrease sum \n\nas i already satated want to delete something everyday and deleting some index again doesn\'t helps so maximum possible days can be n\n\n\nnow how we select elements ?\ni\'ll be using knap sack approach to maximize negative part by selecting t values from n length array \nbut wait ! we have seen that it doesn\'t matter to a1[i] value when ever we select but a2[i] *t matters \nit\'s more benificial to select ``` a2[i] ``` for greater value of t bcz it will maximize our neg part more \nSo we need to sort values arrording to ``` a2 ``` and priorities high value of ``` a2[i] ``` \n\nin case if u have doubt. for a sec forget about time value\nlet\'s say u selected some t elements out of n \nnow u have to subtract these all elemets from our constant sum ( remember for any t it\'s constant ) to minimise the sum, order doesn\'t matter for ``` a1[i] ``` bcz anyway they will get subtracted as it is, but for ```a2[i]*t ```it matters bcz it\'s depends upon order, it\'s wise to delete bigger element late when t is high. \n\nSo this sorting is not for selecting values but for in which order we should subtract those values to maximize negative part, \nin knap sack part all possible ``` t elements ( nCt combiation ) ``` can be selected irrespective of sorting but summation order needs to be in some specific way such that high``` a2[i] ```gets high t value to maximize the solve function that\'s why we need to sort according to ```a2```\n\nImplimentation:\n\nmake a pair of vector : ```{ a2[i],a1[i] } ```\nthen sort it according to first value( default sorting will work )\n\nthen from t=1 to n check is it possible to get ``` sum<=x ```\nmemoize the whole part , solve function is a knapsack approach to select any t element and return max out of it, one thing to notic is we are using precalculated solutions as well like when we call for ```solve(n-1,i+1)``` we are taking use of already solved solution of``` (n-1, i) ``` by using memoization\n\n**Time : NxN\nSpace : NxN**\n\n\n```\nclass Solution {\npublic:\n vector<pair<int,int>> a;\n long long dp[1001][1001];\n long long solve(int idx, int t)\n {\n if(idx<0|| t==0) return 0;\n if(dp[idx][t]!=-1) return dp[idx][t];\n long long ans=solve(idx-1,t-1)+a[idx].second+t*a[idx].first;\n ans=max(ans, solve(idx-1, t));\n \n return dp[idx][t]=ans;\n \n }\n int minimumTime(vector<int>& a1, vector<int>& a2, int x) \n {\n long long s1=0; for(auto i:a1) s1+=i;\n long long s2=0; for(auto i: a2) s2+=i;\n \n int n=a1.size();\n for(int i=0; i<n; i++) a.push_back({a2[i],a1[i]});\n \n sort(a.begin(),a.end());\n \n if(s1<=x) return 0;\n \n \n memset(dp,-1,sizeof(dp));\n \n for(int i=1; i<=n; i++)\n {\n long long val= solve(n-1,i);\n if(s1+i*s2-val<=x) return i;\n }\n return -1;\n \n }\n};\n``` | 0 | 0 | ['Recursion', 'Memoization', 'C'] | 0 |
minimum-time-to-make-array-sum-at-most-x | O(n ^ 2) Propagation DP | on-2-propagation-dp-by-__beginner-ky8w | Intuition\n Describe your first thoughts on how to solve this problem. \nThe key observation about dp approach is that if we\'re selecting k positions to be ma | __Beginner_ | NORMAL | 2023-10-08T22:20:32.677959+00:00 | 2023-10-14T09:43:58.996026+00:00 | 21 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe key observation about dp approach is that if we\'re selecting $$ k$$ positions to be made $$0$$ at successive intervals then we should select the position with in increasing order of $$nums2[i]$$.\nLet\'s prove this below,\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n$$S$$ = sum of values in nums1\n$$A$$ = sum of values in nums2\n\nThe final value after $$i$$ seconds without making any operations on the array will be: $$S + A * i$$\n\nNow imagine the situation after $$i$$ seconds as a 2D matrix where first row is $$nums1$$ and next $$i$$ rows are same as $$nums2$$ array\n\nAt this point of time we have to try to minimize the total sum of the matrix. At $$i$$ seconds we can select at max $$i$$ columns make all their elements from $$time = 0$$ to some $$time <= i$$. So obviously we\'ve to try to select maximum possible ending time to reduce the matrix sum. But we have to select only distinct time instants. i.e. we cannot select same row number for any two columns. Think a little and you\'ll find that the column in which value of $$nums2[i]$$ is maximum should be selected most later in time to kill more occurrances of $$nums2[i]$$ in matrix. This would lead to a conclusion that we have select the columns in increasing order of $$nums2[i]$$.\n\nIf we rearrange the values $$nums2$$ along with their corresponding $$nums1$$ values, it wouldn\'t affect the answer.\n\nSo now pair $$nums1$$ and $$nums2$$ and sort it according increasing order of $$nums2$$ to make it easier for applying dynamic programming on it.\n\n## Understanding dp approach:\nfor simplification:\n$$a = nums1$$\n$$b = nums2$$\n\nAfter time $$k$$, we\'ll have $$k$$ columns where we\'ve applied the operations and $$n - k$$ columns where no operations been applied\n\nEquation of matrix at time $$k$$ will be:\n\n\n$$[(a[i_1] + b[i_1] * k) + (a[i_2] + b[i_2] * k) + .... + (a[i_(n-k)] + b[i_(n-k)])] - [(a[j_1] + b[j_1]) + (a[j_2] + 2 * b[j_2]) + .... + (a[j_k] + k * b[j_k])]$$\n\nso basically we have to maximize the second term which is\n\n$$(a[j_1] + b[j_1]) + (a[j_2] + 2 * b[j_2]) + .... + (a[j_k] + k * b[j_k])$$\nwe can write it as\n$$(a[j_1] + a[j_2] + .... + a[j_k]) + (b[j_1] + 2 * b[j_2] + .... + k * b[j_k])$$\n\nSo basically at time $$k$$ we have to select a subsequence of length $$k$$ which has maximum value of the above expression\n\nconsider $$dp[i][j]$$ here $$i$$ refers to the prefix of the array $$a/b$$ and $$j$$ refers to the time instant $$j$$ and $$dp[i][j]$$ is the maximum sum of a subsequence of length $$j$$ selected from first $$i$$ positions.\n\nwe know that our array $$b$$ is sorted so at the position which is selected at time instant $$j$$ is always greater than the one selected at time instant $$j - 1$$. As we\'re selecting $$b[i]$$ in it\'s increasing order.\n\nlet\'s understand the transtitions to maximize $$dp[i][j]$$.\n- for $$dp[i][j]$$ either we\'d select the current column $$i$$ at $$jth$$ time instant or we do not select it.\n- If we don\'t select it then it means we\'ve already selected $$j$$ positions from first $$i - 1$$ elements.\n- If we select it then we must\'ve selected $$j - 1$$ positions from $$i - 1$$ elements\n\nso final dp equation:\n\n$$dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1] + a[i] + b[i] * j)$$\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n ^ 2 + n *log(n))$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n ^ 2)$$\n# Code\n```\nclass Solution {\npublic:\n int minimumTime(vector<int>& a, vector<int>& b, int x) {\n ios_base::sync_with_stdio(0);\n cin.tie(0); cout.tie(0); cerr.tie(0);\n int n = a.size();\n int sum = accumulate(a.begin(), a.end(), 0);\n int add = accumulate(b.begin(), b.end(), 0);\n vector<pair<int,int>> v(n);\n for(int i = 0; i < n; i++) v[i] = {b[i], a[i]};\n sort(v.begin(), v.end());\n for(int i = 0; i < n; i++) b[i] = v[i].first, a[i] = v[i].second;\n vector<vector<int>> dp(n + 1, vector<int> (n + 1));\n if(sum <= x) return 0;\n for(int i = 1; i <= n; i++){\n for(int j = 1; j <= i; j++){\n dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1] + a[i - 1] + b[i - 1] * j);\n }\n }\n for(int i = 1; i <= n; i++){\n if(sum + add * i - dp[n][i] <= x) return i;\n }\n return -1;\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'C++'] | 0 |
minimum-time-to-make-array-sum-at-most-x | java script - Minimum Time to Make Array Sum At Most x | java-script-minimum-time-to-make-array-s-10d2 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | balakrishnanp | NORMAL | 2023-10-06T11:26:02.452228+00:00 | 2023-10-06T11:26:02.452246+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @param {number} x\n * @return {number}\n */\n// var minimumTime = function(nums1, nums2, x) {\n \n// };\n\nfunction minimumTime(nums1, nums2, x) {\n const n = nums1.length;\n const ind = new Array(n);\n let s = 0;\n let d = 0;\n\n for (let i = 0; i < n; ++i) {\n ind[i] = i;\n s += nums1[i];\n d += nums2[i];\n }\n\n if (s <= x) {\n return 0;\n }\n\n ind.sort((a, b) => {\n return nums2[a] - nums2[b];\n });\n\n const dp = new Array(n + 1).fill(0);\n let r = n + 1;\n\n for (let i = 1; i <= n; ++i) {\n for (let j = Math.min(i, r - 1); j; --j) {\n dp[j] = Math.max(dp[j], dp[j - 1] + nums2[ind[i - 1]] * j + nums1[ind[i - 1]]);\n\n if (s + j * d - dp[j] <= x) {\n r = j;\n }\n }\n }\n\n return r <= n ? r : -1;\n}\n\n// Example usage:\nconst nums1 = [1, 2, 3];\nconst nums2 = [4, 5, 6];\nconst x = 10;\n\nconsole.log(minimumTime(nums1, nums2, x)); // Output: 2\n\n\n\n\n``` | 0 | 0 | ['JavaScript'] | 0 |
minimum-time-to-make-array-sum-at-most-x | C++ DP solution | Intuitive | c-dp-solution-intuitive-by-aglakshya02-fivv | Approach\n Describe your approach to solving the problem. \nYou can watch Coding Mohan\'s YouTube video solution for this, it\'s really difficult to describe th | aglakshya02 | NORMAL | 2023-09-08T11:38:59.501321+00:00 | 2023-09-08T11:38:59.501344+00:00 | 16 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nYou can watch Coding Mohan\'s YouTube video solution for this, it\'s really difficult to describe the solution in a textual post for me.\nMy solution is inspired from his only.\n\n\n# Code\n```\nclass Solution {\npublic:\n\n vector<int>a,b;\n\n int dp[1001][1001];\n\n int maxOp(int col, int ops){\n if(ops==0)return 0;\n if(col<0)return -1e5;\n\n if(dp[col][ops]!=-1)return dp[col][ops];\n\n //take\n int op1 = a[col]+b[col]*ops + maxOp(col-1,ops-1);\n\n //not-take\n int op2 = maxOp(col-1,ops); \n\n return dp[col][ops]=max(op1,op2);\n }\n\n int minimumTime(vector<int>& _a, vector<int>& _b, int x) {\n vector<pair<int,int>>p;\n for(int i=0;i<_a.size();i++){\n p.push_back({_b[i],_a[i]});\n }\n\n sort(p.begin(),p.end());\n\n for(int i=0;i<p.size();i++){\n a.push_back(p[i].second);\n b.push_back(p[i].first);\n }\n\n p.clear(), _a.clear(), _b.clear();\n\n int n=a.size();\n\n memset(dp,-1,sizeof(dp));\n\n int asum=0,bsum=0;\n\n for(int j=0;j<n;j++)\n {\n asum+=a[j];\n bsum+=b[j];\n }\n\n for(int i=0;i<=n;i++){\n int sum=asum+i*bsum;\n if(sum-maxOp(n-1,i)<=x)return i;\n }\n\n return -1;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Unraveling the Optimal Time Scheduler | unraveling-the-optimal-time-scheduler-by-tznv | Intuition\nImagine you have two lists of tasks with respective times required. You have a goal to optimize the sum of these tasks such that, at every step, you | janis__ | NORMAL | 2023-08-29T15:47:42.600716+00:00 | 2023-08-29T15:47:42.600733+00:00 | 11 | false | # Intuition\nImagine you have two lists of tasks with respective times required. You have a goal to optimize the sum of these tasks such that, at every step, you can either use the time from one list or swap it with a time from the other list. The problem might sound tricky, but a methodical approach can reveal patterns that help us arrive at an optimal solution. Our immediate thought here is to prioritize tasks based on which has the most significant benefit when swapped, setting the stage for a dynamic programming solution.\n\n# Approach\n Pairing & Prioritizing Tasks: We start by pairing each task from nums1 with its corresponding task in nums2. The main idea is to figure out which task is most advantageous to swap earlier. This decision is made by sorting these pairs based on the values of nums2. Why? Because when we swap out a value in nums1, the penalty (or addition) we get is from nums2 multiplied by its position. Hence, larger values in nums2 are beneficial to swap out later.\n\n Dynamic Programming Table: We initialize a table, dp, with dimensions (n+1) x (n+1), where n is the number of tasks. This table will help us determine the maximum time reduction possible for any given number of tasks with a set number of operations.\n\n Populating the Table: For each task (in the sorted order), we consider two options:\n a. Not using this task and hence retaining the previous maximum reduction.\n b. Using this task, which means we take the value from nums1 and add a penalty based on its position and value in nums2.\n\n Finding the Minimum Time: Once our table is populated, we go through each time from 0 to n, and check if the total time minus the reduction obtained from our dp table is less than or equal to x (our target). If yes, we return that time.\n\n# Complexity\n- Time complexity:\nO(n^2). The major time consumption happens during the DP table population, which involves nested loops running through the number of tasks.\n\n- Space complexity:\nO(n^2). Primarily due to the space occupied by the DP table. We\'ve also optimized space by utilizing the array data structure, making it more memory-efficient.\n\n# Code\n```\nfrom array import array\n\nclass Solution:\n def minimumTime(self, nums1, nums2, x):\n n = len(nums1)\n \n indices = list(range(n))\n indices.sort(key=lambda i: nums2[i])\n \n dp = [array(\'I\', (0 for _ in range(n + 1))) for _ in range(n + 1)]\n \n for idx in range(1, n + 1):\n a, b = nums1[indices[idx-1]], nums2[indices[idx-1]]\n for j in range(1, n + 1):\n dp[idx][j] = max(dp[idx-1][j], dp[idx-1][j-1] + a + b * j)\n \n sum1 = sum(nums1)\n sum2 = sum(nums2)\n \n for t in range(n + 1):\n prod = sum2 * t\n if sum1 + prod - dp[n][t] <= x:\n return t\n return -1\n\n``` | 0 | 0 | ['Array', 'Dynamic Programming', 'Sorting', 'Python'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Somehow worked, help me optimise the code! | somehow-worked-help-me-optimise-the-code-5e8x | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Chhota_bheem | NORMAL | 2023-08-23T15:30:57.567267+00:00 | 2023-08-23T15:30:57.567297+00:00 | 10 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimumTime(vector<int>& nums1, vector<int>& nums2, int x) {\n \n int n,m,i,j,sum;\n \n n=nums1.size();\n if(n==0)return 0;\n if(n==1){\n if(nums1[0]<=x)return 0;\n return 1;\n }\n \n sum=0;\n vector <pair<int,int> > v1(n);\n for(i=0;i<n;i++)\n {\n v1[i].first=nums1[i];\n v1[i].second=nums2[i];\n sum+=v1[i].first; \n }\n sort(v1.begin(),v1.end(),mysort);\n \n if(sum<=x)return 0;\n \n int p= bnsh(1,n,x,v1,n); \n for(i=max(1,p-10);i<=p;i++)\n if(helper(v1,i,n,x)){\n return i;\n }\n return -1;\n \n \n }\n \n \n int bnsh(int l , int r ,int x, vector <pair<int,int> > &v1, int n){\n int mid;\n mid=(l+r)/2;\n \n \n while(l<=r){\n mid=(l+r)/2; \n //cout<<"l r "<<l<<" "<<r<<" \\n";\n if(helper(v1,mid,n,x)){\n // cout<<"true for mid : "<<mid<<" \\n";\n if(mid==l || !helper(v1,mid-1,n,x))return mid;\n r=mid-1; \n }\n else {\n l=mid+1; \n } \n \n } \n \n return -1; \n \n }\n \n \n \n static bool mysort(pair<int,int> a, pair<int,int> b){\n if(a.second==b.second)\n return a.first>b.first;\n return a.second>b.second;\n }\n \n bool helper(vector <pair<int,int> > &v1, int t, int n , int x){\n int i,j,sum; sum=0; \n \n for(i=0;i<n;i++){\n sum=sum +(v1[i].first + t*(v1[i].second)); \n }\n if(t<=0 || n<1)return (sum<=x);\n \n //cout<<"sum :"<<sum<<"\\n";\n vector<vector <int> > discount(n,vector <int>(t,0));\n \n discount[0][0]=v1[0].first + t*(v1[0].second); \n for(i=1;i<n;i++){\n discount[i][0]=max(discount[i-1][0],v1[i].first + t*(v1[i].second)); //base case \n } \n \n for(i=1;i<n;i++){\n for(j=1;j<=min(i,t-1);j++){\n if(i==j){\n discount[i][j]=discount[i-1][j-1] + (t-j)*v1[i].second + v1[i].first ; \n } \n else discount[i][j] = max(discount[i-1][j], (discount[i-1][j-1] + (t-j)*v1[i].second + v1[i].first)); \n \n }\n //cout<<"\\n";\n }\n \n \n \n sum-=discount[n-1][t-1]; \n \n //cout<<"sum :"<<sum<<"\\n"; \n return (sum<=x);\n \n } \n \n \n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Get the correct DP state before thinking of solution ! | get-the-correct-dp-state-before-thinking-1uk8 | Intuition\nYou need to think of correct dp state in this question.\nIf we calculate to what extent you can reduce the sum of nums1 in each operation we can get | pshreyansh26 | NORMAL | 2023-08-21T17:40:07.426443+00:00 | 2023-08-21T17:40:33.070053+00:00 | 22 | false | # Intuition\nYou need to think of correct dp state in this question.\nIf we calculate to what extent you can reduce the sum of nums1 in each operation we can get the answer.\n\n# Approach\n* Let dp[i][j] represent the maximum total value that can be reduced if we do j operations on the first i elements\n* It can also be proven that if we select several indexes i1, i2, ..., ik and set nums1[i1], nums1[i2], ..., nums1[ik] to 0, it\u2019s always optimal to set them in the order of nums2[i1] <= nums2[i2] <= ... <= nums2[ik] (the larger the increase is, the later we should set it to 0).\n* Let\u2019s sort all the values by nums2 (in non-decreasing order). Let dp[i][j] represent the maximum total value that can be reduced if we do j operations on the first i elements. Then we have dp[i][0] = 0 (for all i = 0, 1, ..., n) and dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1] + nums2[i - 1] * j + nums1[i - 1]) (for 1 <= i <= n and 1 <= j <= i).\n* The answer is the minimum value of t, such that 0 <= t <= n and sum(nums1) + sum(nums2) * t - dp[n][t] <= x, or -1 if it doesn\u2019t exist.\n\n\n\n# Complexity\n- Time complexity:\nO(N^2)\n\n- Space complexity:\nO(N^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimumTime(vector<int>& nums1, vector<int>& nums2, int x) {\n int n = nums1.size();\n vector<vector<int>> dp(n+1,vector<int> (n+1));\n vector<pair<int,int>> numssort(n);\n for(int i=0;i<n;i++) numssort[i] = {nums2[i],i};\n sort(numssort.begin(),numssort.end());\n for(int i=1; i<=n;i++){\n for(int j=1;j<=i;j++){\n int x = numssort[i-1].first;\n int y = nums1[numssort[i-1].second];\n dp[i][j] = max(dp[i-1][j],dp[i-1][j-1] + x*j + y);\n }\n } \n int ans = n+1;\n int sum1 = 0 ,sum2 = 0;\n sum1 = accumulate(nums1.begin(),nums1.end(),sum1);\n sum2 = accumulate(nums2.begin(),nums2.end(),sum2);\n for(int t=0;t<=n;t++){\n if(sum1 + sum2*t - dp[n][t] <= x){\n ans = t;\n break;\n }\n }\n return (ans==n+1)?-1:ans;\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'Sorting', 'C++'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Python | DP | Concise Solution | O(n^2) | python-dp-concise-solution-on2-by-aryonb-ktre | Code\n\nclass Solution:\n def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:\n sum1 = sum(nums1)\n sum2 = sum(nums2)\n | aryonbe | NORMAL | 2023-08-13T11:12:14.245439+00:00 | 2023-08-13T11:12:14.245461+00:00 | 21 | false | # Code\n```\nclass Solution:\n def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:\n sum1 = sum(nums1)\n sum2 = sum(nums2)\n nums = sorted(list(zip(nums2, nums1)))\n n = len(nums)\n dp = [0]*(n+1)\n for i in range(n):\n for k in range(i+1, 0, -1):\n dp[k] = max(dp[k], dp[k-1] + nums[i][0]*k + nums[i][1])\n for k in range(n+1):\n if sum1 + k*sum2 -dp[k] <= x:\n return k \n return -1\n\n\n\n``` | 0 | 0 | ['Python3'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Python | DP | O(n^2) | python-dp-on2-by-aryonbe-i2ri | Code\n\nclass Solution:\n def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:\n sum1 = sum(nums1)\n if sum1 <= x: return | aryonbe | NORMAL | 2023-08-13T09:14:24.727368+00:00 | 2023-08-13T09:14:56.548495+00:00 | 10 | false | # Code\n```\nclass Solution:\n def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:\n sum1 = sum(nums1)\n if sum1 <= x: return 0\n sum2 = sum(nums2)\n nums = sorted(list(zip(nums2, nums1)))\n n = len(nums)\n dp = [0]*n\n for k in range(1,n+1):\n newdp = [0]*n\n for i in range(k-1, n):\n newdp[i] = max(newdp[i-1] if i else 0,(dp[i-1] if i else 0)+nums[i][0]*k+nums[i][1])\n if sum1 + k*sum2 - newdp[-1] <= x:\n return k\n dp = newdp\n return -1\n``` | 0 | 0 | ['Python3'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Easy to understand Recursive DP |Memorization✅ | easy-to-understand-recursive-dp-memoriza-8kvp | \n# Complexity\n- Time complexity:\n- O(N^2)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:\n- O(N^2)\n Add your space complexity here, e.g. | rahulhind | NORMAL | 2023-08-12T10:55:23.535201+00:00 | 2023-08-12T10:56:07.419527+00:00 | 41 | false | \n# Complexity\n- Time complexity:\n- O(N^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(N^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n\nvector<vector<long long> > dp;\nvector<pair<long long,long long> > arr;\nlong long f(int i,int k){\nif(i>=arr.size())return 0;\nif(arr.size()-i<k)return -1e16; //If time remains more than number of elements\n\nif(dp[i][k]!=-1)return dp[i][k];\n\nlong long int t=-1e16;\nif(k>0)\nt= arr[i].first*k+arr[i].second+f(i+1,k-1);\n\n\nlong long int nt=f(i+1,k);\n\nreturn dp[i][k]=max(t,nt);\n\n}\nclass Solution {\npublic:\n\n\n int minimumTime(vector<int>& nums1, vector<int>& nums2, int x) {\n int n=nums1.size();\n arr.clear();\ndp=vector<vector<long long> >(n+1,vector<long long>(n+1,-1));\n for(int i=0;i<nums1.size();i++){\n arr.push_back({nums2[i],nums1[i]});\n }\n sort(arr.rbegin(),arr.rend());\n\n for(int i=0;i<=n;i++){\n long long total=0;\n for(int j=0;j<nums2.size();j++){\n total+=arr[j].first*i+ arr[j].second;\n }\n long long t=f(0,i);\n\n if(total-t<=x){\n return i;\n }\n }\n return -1;\n }\n};\n``` | 0 | 0 | ['C++'] | 1 |
minimum-time-to-make-array-sum-at-most-x | Solution in Swift, DP | solution-in-swift-dp-by-sergeyleschev-38as | Approach\nWe begin by calculating the total sum of the arrays A and B as sa and sb respectively.\n\nIf no actions are taken, at i seconds, we would have a total | sergeyleschev | NORMAL | 2023-08-12T06:16:50.832911+00:00 | 2023-08-12T06:16:50.832936+00:00 | 2 | false | # Approach\nWe begin by calculating the total sum of the arrays A and B as sa and sb respectively.\n\nIf no actions are taken, at i seconds, we would have a total of sb * i + sa.\n\nDuring the t seconds, we select t elements. When we consider these selected elements, A[i] would be removed. The sum for these selected elements would be b1 * (t - 1) + b2 * (t - 2) + ... + bt * 0, where b1, b2, b3, ..., bt are arranged in increasing order.\n\nTo solve this problem, we sort all the pairs (B[i], A[i]) based on the value of B[i].\n\nWe then utilize dynamic programming (dp) with the following logic:\ndp[j][i] represents the maximum value we can reduce within i seconds, using j + 1 step-smallest integers.\n\nThe dp equation is as follows:\ndp[j][i] = max(dp[j][i], dp[j - 1][i - 1] + i * b + a)\n\nIn the end, we return the value of i seconds if sb * i + sa - dp[n - 1][i] is less than or equal to x. If not, we return -1.\n\nIt is possible to optimize the space complexity by storing only the first dimension of the dp array.\n\n# Complexity\n- Time complexity: `O(n^2)`\n- Space complexity: `O(n)`\n\n# Code\n```\nclass Solution {\n func minimumTime(_ nums1: [Int], _ nums2: [Int], _ x: Int) -> Int {\n let n = nums1.count\n var dp = [Int](repeating: 0, count: n + 1)\n \n let sortedPairs = zip(nums2, nums1).sorted { $0.0 < $1.0 }\n \n for (j, (b, a)) in sortedPairs.enumerated() {\n for i in stride(from: j + 1, through: 1, by: -1) {\n dp[i] = max(dp[i], dp[i - 1] + i * b + a)\n }\n }\n \n let sa = nums1.reduce(0, +)\n let sb = nums2.reduce(0, +)\n \n for i in 0...n {\n if sb * i + sa - dp[i] <= x {\n return i\n }\n }\n \n return -1\n }\n}\n\n``` | 0 | 0 | ['Swift'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Dp solution - thinking process and detailed proof | dp-solution-thinking-process-and-detaile-26kp | Intuition\n Describe your first thoughts on how to solve this problem. \nFirst thing that came to my mind afer reading the problem statement was using binary se | horizon1006 | NORMAL | 2023-08-11T08:06:25.405927+00:00 | 2023-08-11T08:10:16.699230+00:00 | 30 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst thing that came to my mind afer reading the problem statement was using binary search but found a counter example shortly thereafter. Take a glance at the constraints, it is not hard to deduce that a $$O(n^2)$$ approach should be used. With this in mind, dynamic programming is the second approach I tried tackling this problem. Here not only do I provide the approach, but also explain my thinking process in order to come up with such a solution.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Let `n` denote the length of `nums1`. If a solution exists, it can not exceed `n`.\n\n\n <details>\n <summary><b>Proof</b></summary>\n \n \n No index should be chosen more than once. If it had been chosen twice, we could have chosen no index in its first time instead and the sum would have remained the same. As each index is chosen at most one, therefore the answer is at most `n` (if exists).\n\n </details>\n\n2. How do we check if a solution for `x` seconds exists. Without loss of generality, let `tot` and `inc` denote the sum of `nums1` and `nums2` respectively, suppose that the 1st till `x`th index were chosen in their respective order (1st index was chosen at time 1, 2nd index was chosen at time 2, etc...), the the current sum is $$tot + inc * x - (nums1[1] + num2[1] * 1 + nums1[2] + num2[2] * 2 ... + nums1[x] + nums2[x] * x) $$. We would like to make this sum as small as possible. The first term $$tot + inc * x$$ is fixed, therefore we maximize the second term. To do so, we must carefully choose the set of x distinct elements and arrange them in an optimal order so that the sum is maximal. We don\'t know which `x` elements should be chosen yet, but for a fixed set of `x` elements, their order can easily be selected. We just need to order them in increasing order of `nums2[i]`, if there\'s a tie, we use `nums1[i]` to break it. The proof is simple, if there were two elements `i` and `j` in which `i` had been choosen earlier than `j` and `nums2[i]` > `nums2[j]`, we can always swap `i` and `j` and the sum would not decrease, hence a more optimal solution.\n \n3. We knew how to order a fixed set of elements, but which elements should we choose ? Dynamic prograaming comes to the rescue!!. If we sort the two arrays by `nums2[i]` then the problem can be rephrased as:\n Given two arrays nums1 and nums2. For a fixed number x, choose x elements such that the sum $$nums1[a] + nums2[a] * 1 + nums2[b] + nums2[b] * 2 + .. nums1[n] + nums2[n] * n$$ under $$ a < b < c .. < n$$. The sollution for this problem is straightforward, it is a variant of knapsack, I\'ll leave it as an exercise for you guys. \n\nAfter having got the answer for each x, for each x from 0 to n, if the value of the equation does not exceed the target, we return x as our final answer. Otherwise, no solution exists.\n\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def minimumTime(self, nums1: List[int], nums2: List[int], target: int) -> int:\n a = sorted(zip(nums2, nums1))\n n = len(nums1)\n inf = 10 ** 18\n dp = [-inf] * (n+1)\n dp[0] = 0\n for y, x in a:\n for i in range(n, 0, -1):\n dp[i] = max(dp[i], dp[i-1] + x + y * i)\n tot = sum(nums1)\n inc = sum(nums2)\n for i in range(n+1):\n if tot + inc * i - dp[i] <= target:\n return i\n return -1\n\n``` | 0 | 0 | ['Python3'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Easy dp solution in c++. | easy-dp-solution-in-c-by-isheoran-oodk | Intuition\nDP\n\n\n# Complexity\n- Time complexity:\n O(n^2)\n\n- Space complexity:\n O(n) \n\n# Code\n\nclass Solution {\npublic:\n int minimumTime(vector<i | isheoran | NORMAL | 2023-08-10T09:59:35.976926+00:00 | 2023-08-10T09:59:35.976952+00:00 | 20 | false | # Intuition\nDP\n\n\n# Complexity\n- Time complexity:\n $$O(n^2)$$\n\n- Space complexity:\n $$O(n)$$ \n\n# Code\n```\nclass Solution {\npublic:\n int minimumTime(vector<int>& nums1, vector<int>& nums2, int x) {\n int n = nums1.size();\n\n vector<pair<int,int>>pr;\n for(int i=0;i<n;i++) pr.push_back({nums2[i],nums1[i]});\n sort(pr.begin(),pr.end());\n\n int sma = 0 , smb = 0;\n\n for(auto [u,v]:pr) {\n smb += u;\n sma += v;\n }\n\n vector<int>dp(n+1);\n \n for(auto [b,a]:pr) {\n for(int i=n;i>0;i--) {\n dp[i] = max(dp[i],dp[i-1]+i*b+a);\n }\n }\n\n for(int i=0;i<=n;i++) {\n if(x >= sma+i*smb - dp[i]) return i;\n }\n\n return -1;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Java | java-by-tetttet-p2di | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | tetttet | NORMAL | 2023-08-09T13:41:48.292293+00:00 | 2023-08-09T13:41:48.292324+00:00 | 18 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minimumTime(List<Integer> A, List<Integer> B, int x) {\n int n = A.size(), sa = 0, sb = 0, dp[] = new int[n + 1];\n List<List<Integer>> BA = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n int a = A.get(i), b = B.get(i);\n BA.add(Arrays.asList(b, a));\n sa += a;\n sb += b;\n }\n Collections.sort(BA, (o1, o2) -> Integer.compare(o1.get(0), o2.get(0)));\n for (int j = 0; j < n; ++j)\n for (int i = j + 1; i > 0; --i)\n dp[i] = Math.max(dp[i], dp[i - 1] + i * BA.get(j).get(0) + BA.get(j).get(1));\n for (int i = 0; i <= n; ++i)\n if (sb * i + sa - dp[i] <= x)\n return i;\n return -1;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Rust | not DP | rust-not-dp-by-tifv-yn9x | Let $n$ be the length of the given arrays, and let $a_{i}$ and $b_{i}$ represent the values of the arrays nums1 and nums2, respectively, $i = 1, \ldots, n$.\n\n | tifv | NORMAL | 2023-08-09T08:07:53.046607+00:00 | 2023-08-09T08:07:53.046629+00:00 | 16 | false | Let $n$ be the length of the given arrays, and let $a_{i}$ and $b_{i}$ represent the values of the arrays `nums1` and `nums2`, respectively, $i = 1, \\ldots, n$.\n\nThere is no point in choosing the same index twice, or delaying operations in time. Therefore, if we are to minimize the obtained sum in time $T$, we will apply operation to some distinct indices $i_{1}$, $i_{2}$, \u2026, $i_{T}$. It follows $T \\leq n$.\n\nAlso, the order of applying the operation to the given indices with the given $T$ is determined by $b_{i_{1}} \\leq b_{i_{2}} \\leq \\ldots \\leq b_{i_{T}}$, and the minimum obtained sum will be\n$\\sum_{i = 1}^{n} (a_{i} + T \\cdot b_{i}) - \\sum_{k = 1}^{T} (a_{i_{k}} - k \\cdot b_{i_{k}})$.\n\nWe will step through $T = 0, \\ldots, n$. For each $T$ we will determine the set of indices to which the operation will be applied, and check whether the obtained sum is less than given `x`.\n\n*Lemma.* Suppose that for time $T < n$ it is known that in order to minimize the sum the operation can be applied to the indices $i_{1}$, $i_{2}$, \u2026, $i_{T}$ in some order. Then for time $T + 1$ the operation can be applied to the same set of indices plus one of the remaining indices, namely $i$ such that the the sum $a_{i} + \\sum_{k = 1}^{T} \\max(b_{i}, b_{i_{k}})$ is the largest.\n\nThis lemma allows us to construct the set of indices iteratively. We will maintain the array $\\left\\lbrace a_{i} + \\sum_{k = 1}^{T} \\max(b_{i}, b_{i_{k}}) \\right\\rbrace_{i=1}^{n}$ to make the search for the next index linear. We will also maintain the set of chosen indices sorted by $b_{i}$ to make computation of the minimum sum linear as well.\n\n# Complexity\n- Time complexity: $O(n^2)$.\n\n- Space complexity: $O(n)$.\n\n# Code\n```\nimpl Solution {\n\n pub fn minimum_time(nums1: Vec<i32>, nums2: Vec<i32>, x: i32) -> i32 {\n let sum1: i32 = nums1.iter().sum();\n let sum2: i32 = nums2.iter().sum();\n let mut rating = std::collections::BTreeSet::new();\n let mut indices = Self::indices(&nums1, &nums2);\n loop {\n let time = rating.len() as i32;\n if ( sum1 + sum2 * time\n - rating.iter().enumerate()\n .map( |(i, &(num2, num1, _))|\n num1 + num2 * (i as i32 + 1) )\n .sum::<i32>()\n ) <= x {\n return time;\n }\n if let Some(index) = indices.next() {\n rating.insert((nums2[index], nums1[index], index));\n } else {\n return -1;\n }\n }\n }\n\n pub fn indices<\'a>(\n nums1: &\'a Vec<i32>, nums2: &\'a Vec<i32>,\n ) -> impl Iterator<Item=usize> + \'a {\n let n = nums1.len();\n let mut eff_nums = (0..n)\n .map(|i| Some(nums1[i] + nums2[i]))\n .collect::<Vec<_>>();\n (0..n).map(move |_| {\n let index = eff_nums.iter().copied().enumerate()\n .filter_map(|(i, maybe_x)| maybe_x.map(|x| (i, x)))\n .max_by_key(|&(_, x)| x)\n .expect("should not yet exhaust all the indices")\n .0;\n eff_nums[index] = None;\n for i in 0..n {\n let num_mut = match &mut eff_nums[i] {\n None => continue,\n Some(num_mut) => num_mut,\n };\n *num_mut += i32::max(nums2[i], nums2[index]);\n }\n index\n })\n }\n\n}\n\n``` | 0 | 0 | ['Rust'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Binary Search + Dp solution | binary-search-dp-solution-by-aryanfit007-mwwg | Approach\nBinary Search + Dp\n\n# Complexity\n- Time complexity: nLogn\n\n# Code\n\nclass Solution {\npublic:\n int dp[1004][1004];\n int recur(int i,int | aryanfit007 | NORMAL | 2023-08-08T20:21:17.269819+00:00 | 2023-08-08T20:21:17.269848+00:00 | 81 | false | # Approach\nBinary Search + Dp\n\n# Complexity\n- Time complexity: nLogn\n\n# Code\n```\nclass Solution {\npublic:\n int dp[1004][1004];\n int recur(int i,int k, vector<int> &v,vector<pair<int,int>> &p,int op){\n if(i==v.size() && k==0) return 0;\n if(i==v.size() && k!=0) return 100000;\n if(dp[i][k]!=-1) return dp[i][k];\n int ans = recur(i+1,k,v,p,op) + v[p[i].second] + op*(p[i].first);\n if(k!=0){\n ans = min(ans,recur(i+1,k-1,v,p,op) + (k-1)*p[i].first); \n }\n return dp[i][k] = ans;\n }\n int minimumTime(vector<int>& nums1, vector<int>& nums2, int target) {\n vector<pair<int,int>> v;\n int sum = 0;\n for(int i=0;i<nums2.size();i++){\n v.push_back({nums2[i],i});\n sum+=nums1[i];\n }\n if(sum<=target) return 0;\n sort(v.begin(),v.end());\n int n = nums1.size();\n int lo = 1;\n int hi = n;\n int mid;\n while(lo<=hi){\n mid = (lo+hi)/2;\n memset(dp,-1,sizeof(dp));\n if(target>=recur(0,mid,nums1,v,mid))\n hi = mid -1;\n else lo = mid +1;\n }\n \n if(hi>=n) return -1;\n memset(dp,-1,sizeof(dp));\n if(target>=recur(0,1,nums1,v,1)) return 1;\n return hi+1;\n\n }\n};\n``` | 0 | 1 | ['Binary Search', 'Dynamic Programming', 'Greedy', 'C++'] | 2 |
minimum-time-to-make-array-sum-at-most-x | Recursive DP solution with intuition | recursive-dp-solution-with-intuition-by-bf58g | Intuition\n Describe your first thoughts on how to solve this problem. \nThe actual complication in the problem is in deciding which array should we sort.\nTo h | kartikeysemwal | NORMAL | 2023-08-08T16:48:55.950351+00:00 | 2023-08-08T16:48:55.950383+00:00 | 82 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe actual complication in the problem is in deciding which array should we sort.\nTo help this simplify, understand that elements in nums1 contribute only once to every index while nums2 contribute at every second.\neg. nums1: [500, 100], nums2: [1, 100]\nAt t=1, [501, 200]\nAt t=2, [502, 300]\nAt t=3, [503, 400]\nAt t=4, [504, 500]\nAt t=5, [505, 600]\n\nFrom above example you see, although the value at index 0 for nums1 was greater but with time value at index 1 overtook it. So sorting should be done based on the values present in nums2.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSort the array based on num2\nApply recursive dp solution for finding answer for each time from t=1 to n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2), as we are calculating the value of 2d array\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n\n# Code\n```\nclass Solution {\n\n int dp[][];\n boolean vis[][];\n\n int solve(List<Integer> nums1, List<Integer> nums2, ArrayList<Integer> indexAl, int curTime, int curIndex) {\n int n = nums1.size();\n\n if (curIndex >= n || curTime <= 0) {\n return 0;\n }\n\n if (vis[curIndex][curTime]) {\n return dp[curIndex][curTime];\n }\n\n int actualIndex = indexAl.get(curIndex);\n\n int ans = 0;\n\n // first option, can skip making it zero\n ans = nums1.get(actualIndex) + nums2.get(actualIndex) * (curTime)\n + solve(nums1, nums2, indexAl, curTime - 1, curIndex + 1);\n\n ans = Math.max(ans, solve(nums1, nums2, indexAl, curTime, curIndex + 1));\n\n vis[curIndex][curTime] = true;\n dp[curIndex][curTime] = ans;\n\n return ans;\n }\n\n public int minimumTime(List<Integer> nums1, List<Integer> nums2, int target) {\n int ans = -1;\n int n = nums1.size();\n\n ArrayList<Integer> indexAl = new ArrayList<>();\n\n int sumNums1 = 0;\n int sumNums2 = 0;\n\n for (int i = 0; i < n; i++) {\n indexAl.add(i);\n\n sumNums1 = sumNums1 + nums1.get(i);\n sumNums2 = sumNums2 + nums2.get(i);\n }\n\n if (sumNums1 <= target) {\n return 0;\n }\n\n Collections.sort(indexAl, (a, b) -> {\n return nums2.get(b) - nums2.get(a);\n });\n\n dp = new int[n + 1][n + 1];\n vis = new boolean[n + 1][n + 1];\n\n for (int i = 1; i <= n; i++) {\n solve(nums1, nums2, indexAl, i, 0);\n\n if (sumNums1 + sumNums2 * i - dp[0][i] <= target) {\n ans = i;\n break;\n }\n }\n\n return ans;\n }\n}\n``` | 0 | 0 | ['Dynamic Programming', 'Recursion', 'Java'] | 0 |
minimum-time-to-make-array-sum-at-most-x | 2d DP | O(n^2) Time, O(n) space. | 2d-dp-on2-time-on-space-by-xun6000-ozxn | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires us to find the minimum time needed to make the sum of the elements | xun6000 | NORMAL | 2023-08-08T00:32:27.655737+00:00 | 2023-08-08T00:32:27.655762+00:00 | 30 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires us to find the minimum time needed to make the sum of the elements in **nums1** less than or equal to **x**. Every second, we can increment the elements of **nums1** by corresponding values in **nums2**, and we can also choose one element in **nums1** to set to 0.\n\n- Since setting the same position to 0 twice would be redundant, we can infer that the maximum time required would be equal to the length of **nums1**, denoted by **n**.\n- If we decide to reset **k** elements, we would choose them based on the order of their corresponding values in **nums2**. If we reset a larger **nums2[idx]** earlier, the increment would be larger.\n- We can use 2-dimensional Dynamic Programming (DP) to solve this problem. To save memory, we can use two vectors of length **n + 1**. **dp[i][j]** represents resetting **j** elements from the first **i** positions in the sorted **nums2**.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Initialization**: Find the sorted indices of **nums2** and initialize the dp vector with zeros.\n2. **Base Case**: Check if the initial sum of **nums1** is already less than or equal to **x**. If so, return 0.\n3. **Dynamic Programming**: Iterate through each time point, calculate the current sum, and use a new DP vector to calculate the maximum value considering the current time point. Check if the requirement is met and return the time point if so.\n4. **Final Check**: If no time point meets the requirement, return -1.\n\n# Complexity\n- Time complexity: $$O(n^2)$$. The nested loops iterate through **n** elements, resulting in quadratic time complexity.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$. We only use two vectors of length **n + 1**, resulting in linear space complexity.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:\n n = len(nums1)\n idxs = sorted(range(n), key=lambda x:nums2[x])\n dp = [0] * (n + 1)\n base = sum(nums1)\n incr = sum(nums2)\n # If already satisfies the requirement.\n if base <= x:\n return 0\n \n # Now, check each time point.\n for time_point in range(1, n + 1):\n curr_sum = base + incr * time_point\n new_dp = [0] * (n + 1)\n for i in range(time_point, n + 1): # We do not need to select y values from the first x elements if x < y.\n new_dp[i] = max(new_dp[i - 1], dp[i - 1] + nums1[idxs[i - 1]] + time_point * nums2[idxs[i - 1]]) # The i th value has an index i - 1\n if curr_sum - new_dp[i] <= x: # If requirement matches.\n return time_point\n # Exchange\n dp = new_dp\n \n # Not found\n return -1\n``` | 0 | 0 | ['Python3'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Ruby memoization & bsearch solution, explained (100%/100%) | ruby-memoization-bsearch-solution-explai-255x | Intuition\nIf you know how many numbers you\'re going to reset, you can check the total from resetting them in optimal order in O(n^2) time with memoization. U | dtkalla | NORMAL | 2023-08-07T22:53:03.058855+00:00 | 2023-08-07T22:53:03.058876+00:00 | 24 | false | # Intuition\nIf you know how many numbers you\'re going to reset, you can check the total from resetting them in optimal order in O(n^2) time with memoization. Use a binary search to figure out how many numbers to reset.\n\n# Approach\n1. Special cases: if the sum is already low enough return 0; if all numbers must be reset because x and everything in nums2 is 0, return nums1.length.\n2. Create class variables for length and both arrays.\n3. Create a variable for the indices ordering nums2 by value. (If we know we\'re resetting two things that have a different nums2 value, we want to reset the lower one first, since it will increase less.)\n4. More special cases: check if resetting one or no values would work. (This speeds up the code.)\n5. Do a binary search for the numbers from 2 to length (exclusive), and find the lowest that returns a total less than k.\n6. Return the result, or else @len, since we know resetting @len works from the special cases we tested earlier.\n\nHelper function total (find the minimum total from resetting k values):\n1. Create a memo object.\n2. Create a sums array that calculates the value at each index if it\'s *not* reset. (We calculate this multiple times in the next helper function, so this speeds it up.)\n3. Call the other helper function, starting at index 0 and k values to reset.\n\nHelper function change:\nThis iterates throuh the values (in the order of @order) and tries changing k of them. Use memoization to efficiently find the lowest possible total.\n1. If you have negative changes, this situation isn\'t possible. Return infinity so this option is never selected.\n2. Return 0 if you\'ve reached the end of the array.\n3. Return the value stored in memo if it exists.\nTwo options at each index:\n 1. Do not change the value at that index -- increment i and add @sum[i]\n 2. Change that index: decrement changes and multiply by the nums2 value. (Right now it\'s 0, but you\'re going to add @nums2[i] (changes-1) times.)\n4. Take the option with the lowest value, memoize, and return. \n\n# Complexity\n- Time complexity:\n$$O(n^2 * log(n))$$\n\n- Space complexity:\n$$O(n^2)$$\n\n# Code\n```\ndef minimum_time(nums1, nums2, x) # O(n^2 * log(n)) -> (10**3)**2 * 10**1 -> 10**7\n return 0 if nums1.sum <= x\n return nums1.count { |n| n > 0 } if x == 0 && nums2.all? { |k| k == 0 }\n\n @len = nums1.length\n @nums1, @nums2 = nums1, nums2\n \n @order = (0...@len).to_a.sort_by { |i| nums2[i] }\n\n return 1 if total(1) <= x\n return -1 unless total(@len) <= x\n \n res = (2...@len).bsearch do |k|\n total(k) <= x\n end\n \n res || @len\nend\n\ndef total(k)\n @memo = Array.new(@len) { Array.new(k) }\n @sum = (0...@len).to_a.map { |i| @nums1[@order[i]] + k * @nums2[@order[i]] }\n change(0,k)\nend\n\ndef change(i,changes)\n return Float::INFINITY if changes < 0\n return 0 if i == @len\n return @memo[i][changes] if @memo[i][changes]\n \n idx = @order[i]\n \n option1 = change(i+1, changes) + @sum[i]\n option2 = change(i+1, changes-1) + (changes-1) * @nums2[idx]\n \n @memo[i][changes] = [option1,option2].min\nend\n``` | 0 | 0 | ['Ruby'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Easy C++ Solution || Memoization|| O(N^2)🔥🔥 | easy-c-solution-memoization-on2-by-himan-d1fe | Intuition\nBasic intution is that we will iterate a loop over number of operations and at any instant if it satisfies condition of sum of both arrays less than | Himanshu2003 | NORMAL | 2023-08-07T13:22:26.217602+00:00 | 2023-08-07T13:22:26.217630+00:00 | 42 | false | # Intuition\nBasic intution is that we will iterate a loop over number of operations and at any instant if it satisfies condition of sum of both arrays less than or equal to x the return operation else return -1 \n\n# Approach\nThe code defines a class named Solution. It uses two arrays named n1 and n2 to hold the numbers from two different sets. There\'s also a 2D array dp used to store intermediate results.\n\nMaxSum Function: There\'s a function named MaxSum which calculates the maximum possible sum considering a certain row and the last index in that row. It does this recursively while memoizing (storing) the results in the dp array to avoid recalculating.\n\nminimumTime Function: This function takes three inputs - two arrays of numbers (nums1 and nums2) and a target sum x. It sorts the numbers in such a way that for each index, the corresponding elements from nums1 and nums2 together form pairs that are sorted based on values in nums2.\n\nMain Logic: The function then iterates through possible numbers of operations (from 0 to the size of the arrays), and calculates the total sum of both sets of numbers considering the current number of operations. It also calculates the maximum possible sum using the MaxSum function for the given number of operations.\n\nCheck and Return: If the difference between the total sum and the maximum possible sum (using MaxSum) is less than or equal to the target x, it means we can achieve the target sum. So, the function returns the current number of operations. It continues this check for different numbers of operations.\n\nConclusion: If no valid number of operations is found within the loop, it means achieving the target sum is not possible. In that case, the function returns -1.\n\n# Complexity\n- Time complexity:\nO(N^2)\n\n- Space complexity:\n\n\n# Code\n```\nclass Solution {\n int dp[1001][1001]; \n vector<int> n1, n2;\n \n int MaxSum(int row, int last_ind) {\n if (row == 0 || last_ind < 0) return 0;\n \n int& ans = dp[row][last_ind];\n if (ans != -1) return ans;\n \n ans = max (\n MaxSum (row, last_ind - 1),\n (n1[last_ind] + n2[last_ind]*row) + MaxSum (row-1, last_ind-1)\n );\n return ans;\n }\n \npublic:\n int minimumTime(vector<int>& nums1, vector<int>& nums2, int x) {\n int n = nums1.size();\n \n n1.clear(), n2.clear();\n n1.resize(n), n2.resize(n);\n \n vector<pair<int,int>> n2_n1; \n for (int j = 0; j < n; j ++) n2_n1.push_back({nums2[j], nums1[j]});\n sort (n2_n1.begin(), n2_n1.end());\n \n for (int j = 0; j < n; j ++) {\n n1[j] = n2_n1[j].second;\n n2[j] = n2_n1[j].first;\n }\n \n memset(dp, -1, sizeof(dp));\n \n for (int op = 0; op <= n; op ++) {\n int sum = 0;\n for (int j = 0; j < n; j ++) sum += n1[j] + n2[j]*op;\n \n if ((sum - MaxSum(op, n-1)) <= x) return op;\n }\n \n return -1;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Recursion to Tabulation | Java | recursion-to-tabulation-java-by-kumarnis-8h8e | Intuition\nAfter learnings all the important conclusions that :\n- At max we will do single operation on any index\n- for any two numbers a and b from nums2, if | kumarnis89 | NORMAL | 2023-08-07T11:14:19.772848+00:00 | 2023-08-07T11:14:19.772875+00:00 | 35 | false | # Intuition\nAfter learnings all the important conclusions that :\n- At max we will do single operation on any index\n- for any two numbers a and b from nums2, if b>a then b will add more value in every second to the total sum.\nso we will opearate on index i with larger nums2[i] after we operate on all other indices with value < nums2[i]\n# Approach\n- for optimal solution we must reset any index each second\n- func(i,j) -> maximum cut that will incur to the arr[0...i] if we do j operations (obviously in j seconds)\n\nex - nums1 = [1,7,9,4,8,8,1]\n nums2 = [2,2,3,2,0,1,0]\n x = 20\n\nHere n = 7\n- If even after n seconds we did not get sum of array elements which is <=x then return -1\n\nsay func(i,j) will return the maximum cut incurred on [0....i] in j operations\n\n1. func(i,j-1) : this recurrence helps in calculating maximum cut in [0.....i] after all possible operations\n2. func(i-1,j-1) : if we select ith index for jth operation\n3. func(i-1,j) : we are trying to choose index for jth operation, but we did not pick ith index\n\n\n\n\n# Complexity\n- Time complexity:$$O(n^2)$$\n\n- Space complexity:$$O(n^2)$$\n\n# Code\n```\nclass Solution {\n int r = 1001,s1=0,s2=0;\n int[][] dp;\n\n\n private int func(List<Integer> nums1, List<Integer> nums2, int x, Integer[] ind, int i, int op){\n if(op==0) return 0;\n if(i==0){\n if(op>0) return Integer.MIN_VALUE;\n return 0;\n }\n\n if(dp[i][op]!=-1) return dp[i][op];\n\n int a=0,b =0,c=0;\n // In case we do not want to do op number of operations on whole array\n a = func(nums1,nums2,x,ind,i,op-1);\n\n // we decided to calculate maximum cut if we do op number of operations on whole array and we select ith index\n b = nums1.get(ind[i-1])+ op*nums2.get(ind[i-1]) + func(nums1,nums2,x,ind,i-1,op-1);\n\n // we decided to calculate maximum cut if we do op number of operations on whole array and we choose to skip ith index\n c = func(nums1,nums2,x,ind,i-1,op);\n\n int maxcut = Math.max(c,Math.max(a,b));\n if(s1+s2*op-maxcut<=x){\n r = Math.min(r,op);\n }\n return dp[i][op] = maxcut;\n }\n \n public int minimumTime(List<Integer> nums1, List<Integer> nums2, int x) {\n int n = nums1.size();\n\n Integer[] ind = new Integer[n];\n\n for(int i=0;i<n;i++){\n s1+=nums1.get(i);\n s2+=nums2.get(i);\n ind[i] = i;\n }\n\n if(s1<=x) return 0;\n\n //sort based on nums2\n Arrays.sort(ind,(a,b)-> nums2.get(a)-nums2.get(b));\n\n dp = new int[n+1][n+1];\n for(int[] arr : dp) Arrays.fill(arr,-1);\n func(nums1,nums2,x,ind,n,n);\n return r<=n?r:-1;\n }\n}\n```\n\n# Tabulation\n```\nclass Solution {\n public int minimumTime(List<Integer> nums1, List<Integer> nums2, int x) {\n int n = nums1.size(), s1=0, s2=0;\n\n Integer[] ind = new Integer[n];\n\n for(int i=0;i<n;i++){\n s1+=nums1.get(i);\n s2+=nums2.get(i);\n ind[i] = i;\n }\n\n if(s1<=x) return 0;\n\n Arrays.sort(ind,(a,b)-> nums2.get(a)-nums2.get(b));\n\n int[][] dp = new int[n+1][n+1];\n Arrays.fill(dp[0],Integer.MIN_VALUE);\n dp[0][0] = 0;\n \n int r = n +1;\n for(int i=1;i<=n;i++){\n for(int j=1;j<=i;j++){\n dp[i][j] = Math.max(nums1.get(ind[i-1])+ j*nums2.get(ind[i-1]) + dp[i-1][j-1],Math.max(dp[i][j-1],dp[i-1][j]));\n if(s1+s2*j-dp[i][j]<=x){\n r = Math.min(r,j);\n }\n }\n }\n return r<=n?r:-1;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Chinese DP O(n^2) | chinese-dp-on2-by-wuzhenhai-mirs | n\u4E3A\u6570\u7EC4\u957F\u5EA6.\n\n \u89C2\u5BDF\n 1: \u540C\u4E00\u4E2A\u4F4D\u7F6E\u4E0D\u5FC5\u9009\u4E2D\u4E24\u6B21, \u53EA\u9700\u4FDD\u7559\u6 | wuzhenhai | NORMAL | 2023-08-07T03:04:35.515458+00:00 | 2023-08-07T03:09:59.088908+00:00 | 32 | false | n\u4E3A\u6570\u7EC4\u957F\u5EA6.\n\n \u89C2\u5BDF\n 1: \u540C\u4E00\u4E2A\u4F4D\u7F6E\u4E0D\u5FC5\u9009\u4E2D\u4E24\u6B21, \u53EA\u9700\u4FDD\u7559\u6700\u540E\u4E00\u6B21\u9009\u4E2D\u5373\u53EF.\n 2: \u5728\u9009\u4E2D\u7684\u6570\u7EC4\u7D22\u5F15\u96C6\u5408\u4E2D, nums2[i]\u8D8A\u5927\uFF0C"i\u9009\u4E2D\u7F6E\u96F6"\u7684\u65F6\u523B\u9700\u8981\u66F4\u9760\u540E.\n 3: \u65F6\u95F4n\u79D2\u6216\u8005\u4EE5\u4E0A\u65F6, \u6700\u7EC8\u4F18\u5316\u7ED3\u679C\u90FD\u662F\u4E00\u6837\u7684.\n\n \u7B2C\u4E00\u6B65:\n nums1, nums2\u6309nums2\u7684\u503C\u4ECE\u5C0F\u5230\u5927\u540C\u6B65\u6392\u5E8F\n \u7B2C\u4E8C\u6B65:\n M[i][j]: \u524Di+1\u4E2A\u6570\u7EC4\u5143\u7D20\uFF0C\u5982\u679C\u4E25\u683C\u4F7F\u7528j\u79D2\u7684\u6700\u5C0F\u548C.\n\n \u60C5\u51B5:\n 1: M[i][0] = sum(nums1[0:i])\n 2: M[0][j] = 0, \u5982\u679Cj>0\n 3: M[i][j] = min(M[i-1][j]+num1[i]+j*num2[i], M[i-1][j-1]+sum(nums2[0:i-1])), \u5982\u679Ci>=1, j>=1. \n\n \u7B2C3\u79CD\u60C5\u51B5\u89E3\u91CA:\n \u5982\u679Ci\u88AB\u9009\u4E2D, \u6839\u636E\u89C2\u5BDF3, \u4E00\u5B9A\u5728j\u79D2\u88AB\u9009\u4E2D, \u6B64\u65F6\u7F6E0, \u5BF9\u6700\u7EC8\u548C\u4E0D\u4EA7\u751F\u5F71\u54CD.\u4F46\u6B64\u65F6, \u524Di\u4E2A([0,1,...,i-1])\u5728j\u79D2\u65F6, \u90FD\u9700\u8981\u81EA\u589Enums2.\n \u7B2C\u4E09\u6B65:\n \u5728\u6570\u7EC4M[n-1]\u4E2D, \u641C\u7D22\u7B2C\u4E00\u4E2A\u4E0D\u5927\u4E8Ex\u7684\u7D22\u5F15. \u5982\u679C\u6CA1\u6709, \u5219\u8FD4\u56DE-1.\n\n\n\n | 0 | 0 | ['Dynamic Programming'] | 0 |
minimum-time-to-make-array-sum-at-most-x | My Solution | my-solution-by-hope_ma-72xo | \n/**\n * let `n` be the length of the vector `nums1`,\n * which is the length of the vector `nums2` as well.\n *\n * some observations\n * 1. if `accumulate(nu | hope_ma | NORMAL | 2023-08-05T21:04:46.186654+00:00 | 2023-08-05T21:07:06.328804+00:00 | 21 | false | ```\n/**\n * let `n` be the length of the vector `nums1`,\n * which is the length of the vector `nums2` as well.\n *\n * some observations\n * 1. if `accumulate(nums1.begin(), nums1.end(), 0)` is less than or equal to `x`,\n * no operations are needed, so `0` should be returned.\n * 2. for any specific index `i`, 0 <= `i` <= `n` - 1,\n * at most one operation is needed to be performed on it,\n * so the maximum return value should be `n`\n * 3. assume that at some specific seconds `s`,\n * the sum `sum` of all elements of `nums1` is less than or equal to `x`,\n * and the indices on each of which one operation is performed are\n * `i1`, `i2`, ..., `is`\n * where `sum` = (nums1[0] + s * nums2[0]) +\n * (nums1[1] + s * nums2[1]) +\n * ... +\n * (nums1[n - 1] + s * nums2[n - 1]) -\n * operations\n * where `operations` is the value subtracted by\n * performing `s` operations on the indices `i1`, `i2`, ..., `is`\n * assume the following operations sequence is optimal,\n * 1) on the first second, the operation is performed on the index `i1`,\n * so the value `nums1[i1] + 1 * nums2[i1]` should be subtracted\n * 2) on the second second, the operation is performed on the index `i2`,\n * so the value `nums1[i2] + 2 * nums2[i2]` should be subtracted\n * ...\n * s) on the `s`\'th second, the operation is performed on the index `is`,\n * so the value `nums1[is] + s * nums2[is]` should be subtracted\n * so `operations` = (nums1[i1] + 1 * nums2[i1]) +\n * (nums1[i2] + 2 * nums2[i2]) +\n * ... +\n * (nums1[is] + s * nums2[is])\n * = (nums1[i1] + nums1[i2] + ... + nums1[is]) +\n * (1 * nums2[i1] + 2 * nums2[i2] + ... + s * nums2[is])\n * in order to make `operations` maximal, nums2[is] > nums2[is - 1] > ... > nums2[i1]\n *\n * firstly sort `nums2`, and adjust `nums1` accordingly\n * then the dp solution is employed\n * dp[seconds][length] stands for the maximal value of `operations`\n * when time is `seconds` and `seconds` operations are performed on the sub-vector\n * from the index `0` to the index `length - 1`\n * where `seconds` is in the range [0, `n`], both inclusive\n * `length` is in the range [`seconds`, `n`], both inclusive\n *\n * initial:\n * dp[0][length] = 0, where `length` is in the range [0, `n`], both inclusive\n *\n * induction:\n * dp[seconds][length] = max(dp[seconds][length - 1],\n * dp[seconds - 1][length - 1] + nums1[length - 1] + seconds * nums2[length - 1])\n * some explanations\n * there are two options, `option1` and `option2`, for the index `index`, which is equal to `length - 1`\n * 1. no operation is performed on it\n * option1 = dp[seconds][length - 1]\n * 2. one operation is performed on it\n * option2 = dp[seconds - 1][length - 1] + nums1[index] + seconds * nums2[index]\n * dp[seconds][length] should be the minimum value between `option1` and `option2`\n *\n * target:\n * for iterate every `seconds` from `0` to `n`\n * 1. if `total` - `dp[seconds][n]` is less than or equal to `x`, the `seconds` should be the return value\n * 2. otherwise, when the loop finishes, `-1` should be the return value\n * where `total` is (`accumulate(nums1.begin(), nums1.end(), 0)` + `seconds` * accumulate(nums2.begin(), nums2.end(), 0))\n *\n * Time Complexity: O(n * n)\n * Space Complexity: O(n)\n */\nclass Solution {\n public:\n int minimumTime(const vector<int> &nums1, const vector<int> &nums2, const int x) {\n constexpr int range = 2;\n int total = accumulate(nums1.begin(), nums1.end(), 0);\n if (total <= x) {\n return 0;\n }\n \n const int total2 = accumulate(nums2.begin(), nums2.end(), 0);\n const int n = static_cast<int>(nums1.size());\n int indices[n];\n iota(indices, indices + n, 0);\n sort(indices, indices + n, [&nums2](const int lhs, const int rhs) -> bool {\n return nums2[lhs] < nums2[rhs];\n });\n int dp[range][n + 1];\n memset(dp, 0, sizeof(dp));\n int previous = 0;\n int current = 1;\n for (int seconds = 1; seconds < n + 1; ++seconds) {\n for (int length = seconds; length < n + 1; ++length) {\n const int index = indices[length - 1];\n dp[current][length] = max(dp[current][length - 1],\n dp[previous][length - 1] + nums1[index] + seconds * nums2[index]);\n }\n \n total += total2;\n if (total - dp[current][n] <= x) {\n return seconds;\n }\n \n previous ^= 1;\n current ^= 1;\n memset(dp[current], 0, sizeof(dp[current]));\n }\n return -1;\n }\n};\n``` | 0 | 0 | [] | 0 |
minimum-time-to-make-array-sum-at-most-x | Sort + greedy + DP problem, beat 100% C++ | sort-greedy-dp-problem-beat-100-c-by-lon-i9qi | Intuition\n Describe your first thoughts on how to solve this problem. \n\n \n# Approach\n Describe your approach to solving the problem. \n sum = sum(num | longvatrong111 | NORMAL | 2023-08-05T19:59:09.033690+00:00 | 2023-08-05T19:59:09.033716+00:00 | 92 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n \n# Approach\n<!-- Describe your approach to solving the problem. -->\n sum = sum(nums1) + t * sums(nums2)\n Create a table:\n - Each row is values of nums1 after adding nums2 at time t\n - Element is sort by nums2\n\n```\nnums1 5 4 6 7\nnums2 1 2 3 4\n\nt = 1 6 6 9 11\nt = 2 7 8 12 15\nt = 3 8 10 15 19\n```\n\nAt time t, need to find subset of t elements from each row, elements must have distinct column index.\n\nSum of element is value removed from total sum, our work is choosing maximum sum and check if sum of subset >= total sum - x \n\nGreedy property:\nDelete num with bigger nums2 later to maximize value.\nSo if we choose num[i] when t = 1, only choose nums[j], j > i when t = 2 and so on.\n\nAt row 1, we need to find maximum num. Store maximum num in dp[0][j]\n\nAt row 2, for each num[j], need to find maximum num from row 1 which index < j. Store maximum duel nums so far in dp[1][j];\n\nAt row i, assume we choose num[j], we need to find maximum sum of i - 1 num from row 1 -> i - 1, which is stored by dp[i - 1][j - 1]\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n dp table can be simplified to a vector since we only need the last row\n O(n)\n# Code\n```\nclass Solution {\npublic:\n int minimumTime(vector<int>& nums, vector<int>& delta, int x) {\n int n = nums.size();\n\n vector<vector<int>> arr(n, vector<int>(2));\n for (int i = 0; i < n; ++i) {\n arr[i][0] = delta[i];\n arr[i][1] = nums[i];\n }\n std::sort(arr.begin(), arr.end());\n \n int sumNums = 0, sumDelta = 0;\n for (int i = 0; i < n; ++i) {\n delta[i] = arr[i][0];\n nums[i] = arr[i][1];\n sumNums += nums[i];\n sumDelta += delta[i];\n }\n \n if (sumNums <= x) return 0;\n \n vector<int> dp(n, 0);\n int curMax = 0;\n for (int i = 0; i < n; ++i) {\n curMax = std::max(curMax, nums[i] + delta[i]);\n dp[i] = curMax;\n if (dp[i] >= sumNums + sumDelta - x) return 1;\n }\n\n int sum = 0;\n for (int i = 2; i <= n; ++i) {\n sum = sumNums + i * sumDelta;\n \n curMax = 0;\n vector<int> tempDp(n, 0);\n for (int j = i - 1; j < n; ++j) {\n int val = nums[j] + i*delta[j];\n curMax = std::max(curMax, val + dp[j - 1]);\n if (curMax >= sum - x) return i;\n tempDp[j] = curMax;\n }\n for (int j = 0; j < n; ++j) dp[j] = tempDp[j];\n }\n \n return -1;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-time-to-make-array-sum-at-most-x | python with inline explaination | python-with-inline-explaination-by-sasha-6q51 | Intuition\n Describe your first thoughts on how to solve this problem. \nWe can remove nums2 from small to big to let nums1 increase slower.\n\n# Approach\n Des | sashawanchen | NORMAL | 2023-08-05T19:50:27.466875+00:00 | 2023-08-05T19:50:27.466897+00:00 | 17 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can remove nums2 from small to big to let nums1 increase slower.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution(object):\n def minimumTime(self, nums1, nums2, x):\n """\n :type nums1: List[int]\n :type nums2: List[int]\n :type x: int\n :rtype: int\n s1+s2*n\n\n remove smallest nums2[?] pair from 0~i\n dp[i-1]+nums1[i]+nums2[i]*i\n """\n n=len(nums1)\n dp=[0]*(n+1)\n idx=range(n)\n idx.sort(key=lambda x:nums2[x])\n for i in range(1,n+1): # remove nums2 small to big\n for j in range(i,0,-1): #at j sec remove the biggest nums2 for dp[j], 2nd biggest for dp[j-1]\n dp[j]=max(dp[j],dp[j-1]+nums1[idx[i-1]]+nums2[idx[i-1]]*j)\n s1,s2=sum(nums1),sum(nums2)\n for i in range(0,n+1):# start from i==0, means no need to remove any element\n if s1+s2*i-dp[i]<=x:\n return i\n return -1\n\n``` | 0 | 0 | ['Python'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Annotated C++ Solution | annotated-c-solution-by-gyrcpp-v74d | Bog standard c++ implementation based on the question hint.\n\n# Code\ncpp\nclass Solution {\npublic:\n int minimumTime(vector<int>& nums1, vector<int>& nums | gyrcpp | NORMAL | 2023-08-05T17:05:23.480946+00:00 | 2023-08-05T17:06:27.615230+00:00 | 58 | false | Bog standard c++ implementation based on the question hint.\n\n# Code\n```cpp\nclass Solution {\npublic:\n int minimumTime(vector<int>& nums1, vector<int>& nums2, int x) {\n \n // 1.0 Define number of nodes to be used throughout this function.\n int n = nums1.size();\n\n // 1.1 Create a map of each element in nums2 and nums1,\n // allowing for sorting based on the values in nums2.\n vector<pair<int, int>> num2num1;\n for (int i = 0; i < n; i++) {\n num2num1.push_back({nums2[i], nums1[i]});\n }\n sort(num2num1.begin(), num2num1.end());\n\n // 1.2 Create a 2D DP vector.\n vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0));\n\n // 2.0 Populate the DP vector from smallest to largest element\n // in num2, over the number of ops up to n.\n int ops = 1;\n for (auto it = num2num1.begin(); it != num2num1.end(); it++) {\n for (int sec = 1; sec <= ops; sec++) {\n \n int num2 = (*it).first;\n int num1 = (*it).second;\n\n // These two lines are the key to this problem.\n int skipNum2 = dp[ops - 1][sec];\n int useNum2 = dp[ops - 1][sec - 1] + num2 * sec + num1;\n\n dp[ops][sec] = max(skipNum2, useNum2);\n }\n ops++;\n }\n\n // 3.0 Find the smallest time `t` using the dp matrix that\n // satisfies the sum threshold.\n int sum1 = reduce(nums1.begin(), nums1.end());\n int sum2 = reduce(nums2.begin(), nums2.end());\n for (int t = 0; t <= n; t++) {\n if (sum1 + sum2 * t - dp[n][t] <= x) {\n return t;\n }\n }\n\n return -1;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-time-to-make-array-sum-at-most-x | C# || Solution | c-solution-by-vdmhunter-g2ev | \npublic class Solution\n{\n public int MinimumTime(IList<int> nums1, IList<int> nums2, int x)\n {\n var n = nums1.Count;\n\n var p = Enumer | vdmhunter | NORMAL | 2023-08-05T16:42:25.673668+00:00 | 2023-08-14T16:15:19.535122+00:00 | 28 | false | ```\npublic class Solution\n{\n public int MinimumTime(IList<int> nums1, IList<int> nums2, int x)\n {\n var n = nums1.Count;\n\n var p = Enumerable.Range(0, n)\n .Select(i => (a:nums1[i], b:nums2[i]))\n .OrderBy(t => t.b)\n .ToList();\n\n var dp = new int[n + 1];\n\n foreach (var (a, b) in p)\n for (var i = n - 1; i >= 0; i--)\n dp[i + 1] = Math.Max(dp[i + 1], dp[i] + (i + 1) * b + a);\n\n var s1 = nums1.Sum();\n var s2 = nums2.Sum();\n\n for (var i = 0; i <= n; i++)\n if (s2 * i + s1 - dp[i] <= x)\n return i;\n\n return -1;\n }\n}\n\n``` | 0 | 0 | ['C#'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Java | Best Solution | Minimum Time to Make Array Sum At Most x | java-best-solution-minimum-time-to-make-fnsjg | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | shrey163 | NORMAL | 2023-08-05T16:28:26.646619+00:00 | 2023-08-05T16:28:26.646647+00:00 | 104 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minimumTime(List<Integer> nums1, List<Integer> nums2, int x) {\n ArrayList<Integer> ids = new ArrayList<Integer>();\n int n = nums1.size();\n for (int i = 0; i < n; ++i) {\n ids.add(nums2.get(i)*1001+nums1.get(i));\n }\n Collections.sort(ids);\n List<Integer> a = new ArrayList<>();\n List<Integer> b = new ArrayList<>();\n int sum1 = 0;\n int sum2 = 0;\n for (int i = 0; i < n; ++i) {\n b.add(ids.get(i)/1001);\n a.add(ids.get(i)%1001);\n sum1 += a.get(i);\n sum2 += b.get(i);\n }\n int[][] dp = new int[n+1][n+1];\n dp[0][0] = sum1;\n for (int i = 1; i <= n; ++i) {\n dp[0][i] = sum1;\n dp[i][0] = dp[i-1][0]+sum2;\n }\n if (sum1<=x)\n return 0;\n for (int i = 1; i <= n; ++i) {\n for (int j = 1; j <= n; ++j) {\n dp[i][j] = dp[i][j-1];\n dp[i][j] = Math.min(dp[i][j], dp[i-1][j-1]+sum2-a.get(j-1)-b.get(j-1)*i);\n if (dp[i][j]<=x)\n return i;\n }\n }\n return -1;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
online-election | [C++/Java/Python] Binary Search in Times | cjavapython-binary-search-in-times-by-le-t1he | Initialization part\nIn the order of time, we count the number of votes for each person.\nAlso, we update the current lead of votes for each time point.\nif (co | lee215 | NORMAL | 2018-09-23T03:06:50.194904+00:00 | 2021-07-25T08:27:42.440822+00:00 | 20,205 | false | ## **Initialization part**\nIn the order of time, we count the number of votes for each person.\nAlso, we update the current lead of votes for each time point.\n` if (count[person] >= count[lead]) lead = person`\n\nTime Complexity: `O(N)`\n<br>\n\n## **Query part**\nBinary search `t` in `times`,\nfind out the latest time point no later than `t`.\nReturn the lead of votes at that time point.\n\nTime Complexity: `O(logN)`\n\n<br>\n\n**C++**\n```cpp\n unordered_map<int, int> m;\n vector<int> times;\n TopVotedCandidate(vector<int> persons, vector<int> times) {\n int n = persons.size(), lead = -1;\n this->times = times;\n unordered_map<int, int> count;\n for (int i = 0; i < n; ++i) {\n lead = ++count[persons[i]] >= count[lead] ? persons[i] : lead;\n m[times[i]] = lead;\n }\n }\n\n int q(int t) {\n return m[*--upper_bound(times.begin(), times.end(), t)];\n }\n```\n\n**C++, using map**\nTime complexity `O(nlogn)`\n```cpp\n map<int, int> m;\n TopVotedCandidate(vector<int> persons, vector<int> times) {\n int n = persons.size(), lead = -1;\n unordered_map<int, int> count;\n for (int i = 0; i < n; ++i) {\n lead = ++count[persons[i]] >= count[lead] ? persons[i] : lead;\n m[times[i]] = lead;\n }\n }\n\n int q(int t) {\n return (--m.upper_bound(t))-> second;\n }\n```\n\n**Java:**\n```java\n Map<Integer, Integer> m = new HashMap<>();\n int[] time;\n public TopVotedCandidate(int[] persons, int[] times) {\n int n = persons.length, lead = -1;\n Map<Integer, Integer> count = new HashMap<>();\n time = times;\n for (int i = 0; i < n; ++i) {\n count.put(persons[i], count.getOrDefault(persons[i], 0) + 1);\n if (i == 0 || count.get(persons[i]) >= count.get(lead)) lead = persons[i];\n m.put(times[i], lead);\n }\n }\n\n public int q(int t) {\n int i = Arrays.binarySearch(time, t);\n return i < 0 ? m.get(time[-i-2]) : m.get(time[i]);\n }\n```\n\n**Python:**\n```python\n def __init__(self, persons, times):\n self.leads, self.times, count = [], times, {}\n lead = -1\n for p in persons:\n count[p] = count.get(p, 0) + 1\n if count[p] >= count.get(lead, 0): lead = p\n self.leads.append(lead)\n\n def q(self, t):\n return self.leads[bisect.bisect(self.times, t) - 1]\n```\n | 170 | 1 | [] | 35 |
online-election | [Java/Python 3] two methods with comment- using TreeMap and binary search, respectively | javapython-3-two-methods-with-comment-us-jvek | Method 1:\nTime complexity for constructor TopVotedCandidate(int[] persons, int[] times)\tis O(nlogn), and for q(int t) is O(logn).\n\n\tprivate TreeMap tm = ne | rock | NORMAL | 2018-09-23T03:08:32.826941+00:00 | 2022-06-26T20:04:55.327025+00:00 | 5,486 | false | Method 1:\nTime complexity for constructor `TopVotedCandidate(int[] persons, int[] times)`\tis O(nlogn), and for `q(int t)` is O(logn).\n\n\tprivate TreeMap<Integer, Integer> tm = new TreeMap<>(); // time and leading candidate\n\tpublic TopVotedCandidate(int[] persons, int[] times) {\n\t int[] count = new int[persons.length]; // count[i]: count of votes for persons[i].\n\t for (int i = 0, max = -1; i < times.length; ++i) {\n ++count[persons[i]]; // at times[i], persons[i] got a vote.\n if (max <= count[persons[i]]) { // is persons[i] leading?\n max = count[persons[i]]; // update leading count.\n tm.put(times[i], persons[i]); // update leading candidate.\n }\n }\n\t}\n public int q(int t) {\n return tm.floorEntry(t).getValue(); // fetch the corresponding information. \n }\n\nMethod 2: \nHashMap.put() cost only O(1) for each operation. Therefore, \ntime complexity: Constructor O(n), `q(int t)` is O(logn).\n\n\tprivate Map<Integer, Integer> map = new HashMap<>(); // time and leading candidate\n private int[] times;\n public TopVotedCandidate(int[] persons, int[] times) {\n this.times = times;\n int[] count = new int[persons.length + 1]; // count[i]: count of votes for persons[i].\n for (int i = 0, winner = -1; i < times.length; ++i) {\n ++count[persons[i]]; // at times[i], persons[i] got a vote.\n // is persons[i] leading? update winner.\n if (map.isEmpty() || count[winner] <= count[persons[i]]) { \n winner = persons[i]; \n } \n map.put(times[i], winner); // update time and winner.\n }\n }\n public int q(int t) {\n int idx = Arrays.binarySearch(times, t); // search for the time slot.\n return map.get(times[idx < 0 ? -idx - 2 : idx]); // fetch the corresponding information.\n }\n\n```python\n def __init__(self, persons: List[int], times: List[int]):\n votes_count = collections.Counter()\n self.votes_leader = []\n max_votes = -1\n for time, person in zip(times, persons):\n votes_count[person] += 1\n if max_votes <= votes_count[person]:\n max_votes = votes_count[person]\n self.votes_leader.append((time, person)) \n \n def q(self, t: int) -> int:\n return self.votes_leader[bisect.bisect_left(self.votes_leader, (t, math.inf)) - 1][1]\n``` | 43 | 0 | [] | 10 |
online-election | An extremely detailed explanation accompanied with Code. | an-extremely-detailed-explanation-accomp-hgvc | First lets understand the question input as I had a hard time to make sense of question input.\n\n\n ["TopVotedCandidate","q","q","q","q","q","q"], [[[0,1,1 | amrx101 | NORMAL | 2020-06-11T04:06:13.101418+00:00 | 2020-06-11T04:08:33.100407+00:00 | 1,689 | false | First lets understand the question input as I had a hard time to make sense of question input.\n\n\n ["TopVotedCandidate","q","q","q","q","q","q"], [[[0,1,1,0,0,1,0],[0,5,10,15,20,25,30]],[3],[12],[25],[15],[24],[8]]\n\t \nFirst list is the query. Now we have a list of lists. The very first list is a list of persons voted and second list is the time of voting.\n`[0,1,1, 0, 0, 1, 0]`\n`[0,5,10,15,20,25,30]`\n\nThis means at time `t=0` a voted was casted for person `0`, and at time `t=5` one vote was casted for person `1` ans so on.\n\nThe question says that we have to answer the question `who is the leading candidate at t=11 or t=13 or t=2?`.\n\nI hope this clears the question as it did for me.\n\nNow lets take t=11.\nNow `t=11` is not in the list of times. It falls between `t=10` and `t=15`.\n\nProposition: If a `t` is not present in `times` then the leading candidate at `t` will be the same candidate who has been leading at time `t\'` where `t\'` < `t` and `t\'` is the largest element in `times` that satisfies the inequality.\n\nProof: Say `t`= 11. Now we know that 11 is not in `times`. Largest number smaller that 11 in times is 10. Till 10 person `1` is leading[0,1,1]. Person 1 will lead in 11 as well because the next voting occurs at `t=15`. In fact person 1 will keep leading at times 10,11,12,13,14 and may start trailing as per the vote casted at t=15.\n\nSo when given a time `t` our job becomes first to find the time `t\'`. As `times` is always increasing we use binary search here.\n\n def bs(self, t):\n\t\t\tl = 0\n\t\t\tr = len(self.times)-1\n\t\t\tans = -1\n\t\t\twhile l <= r:\n\t\t\t\tm = (l+r)/2\n\t\t\t\tc = self.times[m]\n \n\t\t\t # t is in times.\n\t\t\t\tif c == t:\n\t\t\t\t\treturn m\n\t\t\t\t# we are finding t\' here.\n\t\t\t\telif c < t:\n\t\t\t\t\tans = max(ans, m)\n\t\t\t\t\tl = m+1\n\t\t\t\telse:\n\t\t\t\t\tr = m-1\n\t\t\treturn ans\n\nNow this our work half done.\n\nNow we need to maintain an array where in we keep track of the leading candidate for all `t`s in `times` array.\n\nWe do that during initialization\n\n\n\t\tself.persons = persons\n self.times = times\n self.leaders = []\n res = defaultdict(int)\n leader = 0\n for index, person in enumerate(self.persons):\n res[person] += 1\n if res[person] >= res[leader]:\n leader = person\n self.leaders.append(leader)\n\nPutting all together\n\n from collections import defaultdict\n class TopVotedCandidate(object):\n\n\t\t def __init__(self, persons, times):\n\t\t\t"""\n\t\t\t:type persons: List[int]\n\t\t\t:type times: List[int]\n\t\t\t"""\n\t\t\tself.persons = persons\n\t\t\tself.times = times\n\t\t\tself.leaders = []\n\t\t\tres = defaultdict(int)\n\t\t\tleader = 0\n\t\t\tfor index, person in enumerate(self.persons):\n\t\t\t\tres[person] += 1\n\t\t\t\tif res[person] >= res[leader]:\n\t\t\t\t\tleader = person\n\t\t\t\tself.leaders.append(leader)\n \n\n\t\tdef q(self, t):\n\t\t\t"""\n\t\t\t:type t: int\n\t\t\t:rtype: int\n\t\t\t"""\n\t\t\tt_index = self.bs(t)\n\t\t\t# print t_index\n\t\t\treturn self.leaders[t_index]\n \n\t\tdef bs(self, t):\n\t\t\tl = 0\n\t\t\tr = len(self.times)-1\n\t\t\tans = -1\n\t\t\twhile l <= r:\n\t\t\t\tm = (l+r)/2\n\t\t\t\tc = self.times[m]\n \n\t\t\t\tif c == t:\n\t\t\t\t\treturn m\n\t\t\t\telif c < t:\n\t\t\t\t\tans = max(ans, m)\n\t\t\t\t\tl = m+1\n\t\t\t\telse:\n\t\t\t\t\tr = m-1\n\t\t\t# print ans, len(self.times)-1\n\t\t\treturn ans\n | 21 | 0 | ['Binary Search'] | 5 |
online-election | C++ binary search solution beats 100% | c-binary-search-solution-beats-100-by-bw-qe2p | C++\nclass TopVotedCandidate{\npublic:\n TopVotedCandidate(vector<int> persons, vector<int> times) {\n int max_count = 0, candidate = 0, len = persons | bwv988 | NORMAL | 2019-02-23T09:31:54.245316+00:00 | 2019-02-23T09:31:54.245353+00:00 | 2,059 | false | ```C++\nclass TopVotedCandidate{\npublic:\n TopVotedCandidate(vector<int> persons, vector<int> times) {\n int max_count = 0, candidate = 0, len = persons.size();\n int count[len + 1];\n memset(count, 0, sizeof count);\n // candidates.first is the time[i], candidates.second is the top voted candidate at time[i].\n candidates = vector<pair<int, int>>(len);\n for(int i = 0; i < len; i++){\n count[persons[i]]++;\n if(count[persons[i]] >= max_count){\n max_count = count[persons[i]];\n candidate = persons[i];\n }\n candidates[i].first = times[i];\n candidates[i].second = candidate;\n }\n }\n \n int q(int t) {\n int lo = 0, hi = candidates.size();\n // Find the largest time which <= t, this is equivalent with find the smallest time which > t, then minus 1;\n while(lo < hi){\n int m = (lo + hi) / 2;\n if(candidates[m].first <= t){\n lo = m + 1;\n }else{\n hi = m;\n }\n }\n return candidates[lo - 1].second;\n }\n\t\nprivate:\n vector<pair<int, int>> candidates;\n};\n\n``` | 20 | 1 | [] | 2 |
online-election | Python readable short bisect solution | python-readable-short-bisect-solution-by-rbsn | There is a minor ambiguity in the question btw. If time is taken as zero, there is no chance to decide who is the winner.\n\nclass TopVotedCandidate:\n\n def | cenkay | NORMAL | 2018-09-23T03:16:16.523659+00:00 | 2018-10-23T22:01:17.915677+00:00 | 1,463 | false | There is a minor ambiguity in the question btw. If time is taken as zero, there is no chance to decide who is the winner.\n```\nclass TopVotedCandidate:\n\n def __init__(self, persons, times):\n votes = collections.defaultdict(int)\n winner = 0\n self.winners = [None] * len(times)\n self.times = times\n for i, person in enumerate(persons):\n votes[person] += 1 \n if votes[person] >= votes[winner]:\n winner = person\n self.winners[i] = winner\n\n def q(self, t):\n return self.winners[bisect.bisect(self.times, t) - 1]\n``` | 15 | 1 | [] | 4 |
online-election | JAVA TreeMap | java-treemap-by-caraxin-040c | \nclass TopVotedCandidate {\n TreeMap<Integer, Integer> map= new TreeMap<>();\n public TopVotedCandidate(int[] persons, int[] times) {\n int[] cnt= | caraxin | NORMAL | 2018-09-23T03:07:03.368967+00:00 | 2018-10-02T08:41:14.068715+00:00 | 1,098 | false | ```\nclass TopVotedCandidate {\n TreeMap<Integer, Integer> map= new TreeMap<>();\n public TopVotedCandidate(int[] persons, int[] times) {\n int[] cnt= new int[persons.length];\n int maxCnt=0;\n for (int i=0; i<persons.length; i++){\n int p= persons[i], t= times[i];\n if (++cnt[p]>=maxCnt){\n maxCnt=cnt[p];\n map.put(t, p);\n }\n }\n }\n \n public int q(int t) {\n int time= map.floorKey(t);\n return map.get(time);\n }\n}\n``` | 13 | 1 | [] | 1 |
online-election | Java || With good explaination | java-with-good-explaination-by-nobody10-7gb2 | \n# Approach\nThe TopVotedCandidate class represents the online election system. The constructor takes two arrays as input: persons, which is an array of intege | nobody10 | NORMAL | 2023-03-02T07:53:30.312722+00:00 | 2023-03-02T07:53:30.312766+00:00 | 1,424 | false | \n# Approach\nThe TopVotedCandidate class represents the online election system. The constructor takes two arrays as input: persons, which is an array of integers representing the ID of each person who voted, and times, which is an array of integers representing the time at which each vote was cast. The constructor initializes two arrays: times, which stores the input times array, and leads, which stores the ID of the current leader at each time in the times array.\n\nThe q method takes a time t as input and returns the ID of the leader at that time. This method uses binary search to find the index i of the largest time in the times array that is less than or equal to t. It then returns the leader at that index in the leads array.\n\n# Complexity\n- Time complexity:\nThe time complexity of the constructor is O(N), where N is the length of the input persons and times arrays. This is because we need to iterate through the arrays once to compute the leads array.\n\nThe time complexity of the q method is O(log N), where N is the length of the input times array. This is because we use binary search to find the index of the largest time that is less than or equal to t.\n\n\n\n\n\n\n\n\n- Space complexity:\nThe space complexity of the TopVotedCandidate class is O(N), where N is the length of the input persons and times arrays. This is because we store the input arrays and the leads array, which each take up O(N) space. The space complexity of the q method is O(1), because we only use a constant amount of extra space for the lo, hi, and mid variables used in binary search.\n\n# Code\n```\nclass TopVotedCandidate {\n int[] times;\n int[] leads;\n\n public TopVotedCandidate(int[] persons, int[] times) {\n int n = persons.length;\n this.times = times;\n leads = new int[n];\n\n int[] votes = new int[n];\n int maxVotes = 0, leader = -1;\n\n for (int i = 0; i < n; i++) {\n int p = persons[i];\n int t = times[i];\n\n votes[p]++;\n if (votes[p] >= maxVotes) {\n maxVotes = votes[p];\n leader = p;\n }\n\n leads[i] = leader;\n }\n }\n\n public int q(int t) {\n int lo = 0, hi = times.length - 1;\n while (lo < hi) {\n int mid = (lo + hi + 1) / 2;\n if (times[mid] <= t) {\n lo = mid;\n } else {\n hi = mid - 1;\n }\n }\n return leads[lo];\n }\n}\n\n``` | 6 | 0 | ['Array', 'Hash Table', 'Binary Search', 'Design', 'Java'] | 0 |
online-election | Java | TreeMap | java-treemap-by-tk-x-t8cq | \nclass TopVotedCandidate {\n TreeMap<Integer, Integer> timedWinner;\n int lead;\n public TopVotedCandidate(int[] persons, int[] times) {\n int | TK-X | NORMAL | 2022-06-14T11:36:34.382475+00:00 | 2022-06-14T11:36:34.382513+00:00 | 1,038 | false | ```\nclass TopVotedCandidate {\n TreeMap<Integer, Integer> timedWinner;\n int lead;\n public TopVotedCandidate(int[] persons, int[] times) {\n int n = times.length;\n lead = -1;\n timedWinner = new TreeMap();\n Map<Integer, Integer> votes = new HashMap();\n for(int i=0; i<n; i++){\n votes.put(persons[i], votes.getOrDefault(persons[i], 0)+1);\n if(i==0 || votes.get(persons[i])>=votes.get(lead)){\n lead = persons[i];\n }\n timedWinner.put(times[i], lead); \n }\n }\n \n public int q(int t) {\n return timedWinner.floorEntry(t).getValue();\n }\n}\n\n``` | 5 | 0 | ['Tree', 'Java'] | 1 |
online-election | ✅ [JS] Binary Search Approach w/ explanation 🔥 | js-binary-search-approach-w-explanation-4lpcr | \uD83D\uDC4D In the event that you found my solution to be beneficial, I would be most grateful if you would consider UPVOTING IT. This action would serve as a | ad0x99 | NORMAL | 2024-06-18T15:23:25.308986+00:00 | 2024-11-27T08:58:03.661981+00:00 | 192 | false | **\uD83D\uDC4D In the event that you found my solution to be beneficial, I would be most grateful if you would consider UPVOTING IT. This action would serve as a significant motivator for me to continue providing additional solutions in the future. \uD83D\uDE46\u200D\u2642\uFE0F**\n\n---\n\n# Binary Search Approach\n\n1. We create an `leadingVotes` array that will store the leading candidate for each timestamp (times). And a `times` array to store the input times array in the object\'s property for later reference.\n\n2. We create a `voteCount` that will be used to keep track of the vote count for each person, and a `leading` variable to store the current leading candidate (initially set to 0).\n\n3. **Building Leading Votes**: We iterate through each `person`, and inside the loop:\n - 3.1: We update the vote count for the current person to keep track how much votes the current person has received.\n\n - 3.2: We check if the current person\'s vote count is greater than or equal to the current leading candidate\'s vote count, it means the current person has either taken the lead or tied with the previous leader. We will update the leading variable to the current person to reflect the new or tied leading candidate.\n\n - 3.3: After that, we assign the current leading candidate (leading) to the corresponding timestamp (`times[i]`) in the leadingVotes array. This effectively stores the leading candidate for each time point based on the vote counts processed so far.\n\nAfter building a list of leading votes for each timestamp. Inside the `q` function, we want to find the leading vote at specified time from the `leadingVotes` array using `binary search` (`upper bound` technique).\n\n# Complexity\n\n- Time complexity:\n - `TopVotedCandidate`: `O(n)`, where `n` is the length of `persons` array.\n - `q` method: `O(log n)`, where `n` is the number of `times`.\n\n- Space complexity:\n - `TopVotedCandidate`: `O(n)`, where `n` is the length of `voteCount` map.\n - `q` method: `O(1)`\n\n# Code\n\n```javascript []\nconst TopVotedCandidate = function (persons, times) {\n this.leadingVotes = [];\n this.times = times;\n\n let n = persons.length;\n let voteCount = new Map();\n let leading = 0;\n\n for (let i = 0; i < n; i++) {\n voteCount.set(\n persons[i],\n voteCount.get(persons[i]) ? voteCount.get(persons[i]) + 1 : 1\n );\n\n // Update leading candidate if necessary\n if (voteCount.get(persons[i]) >= voteCount.get(leading)) {\n leading = persons[i];\n }\n\n this.leadingVotes[times[i]] = leading;\n }\n};\n\n// Perform binary search to find the closest time <= t\nTopVotedCandidate.prototype.q = function (t) {\n let left = 0;\n let right = this.times.length - 1;\n let ans = 0;\n\n while (left <= right) {\n let mid = Math.floor((left + right) / 2);\n\n if (this.times[mid] <= t) {\n ans = this.times[mid];\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n\n return this.leadingVotes[ans];\n};\n```\n```rust []\nuse std::collections::HashMap;\n\nstruct TopVotedCandidate {\n leading_votes: Vec<i32>, // Stores the leader at each index of `times`\n times: Vec<i32>, // Stores the voting times\n}\n\nimpl TopVotedCandidate {\n // Constructor\n fn new(persons: Vec<i32>, times: Vec<i32>) -> Self {\n let n = persons.len();\n let mut vote_count = HashMap::new();\n let mut leading_votes = Vec::with_capacity(n);\n let mut leading = -1;\n\n for i in 0..n {\n let person = persons[i];\n *vote_count.entry(person).or_insert(0) += 1;\n\n // Update leading candidate if necessary\n if leading == -1 || vote_count[&person] >= vote_count[&leading] {\n leading = person;\n }\n\n leading_votes.push(leading);\n }\n\n TopVotedCandidate {\n leading_votes,\n times,\n }\n }\n\n fn q(&self, t: i32) -> i32 {\n // Perform binary search to find the closest time <= t\n let mut left = 0;\n let mut right = self.times.len() - 1;\n let mut ans = 0;\n\n while left <= right {\n let mid = (left + right) / 2;\n\n if self.times[mid] <= t {\n ans = mid;\n left = mid + 1; // Search on the right half\n } else {\n right = mid - 1; // Search on the left half\n }\n }\n\n self.leading_votes[ans]\n }\n}\n```\n | 4 | 0 | ['Binary Search', 'Rust', 'JavaScript'] | 0 |
online-election | Python | Precompute + Binary Search | python-precompute-binary-search-by-sr_vr-pcl7 | For __init__ we precompute the top voted person for each time in times in an ordered list topVoted.\n* For q we use Binary Search in topVoted (recycling code fr | sr_vrd | NORMAL | 2022-05-14T06:40:57.776676+00:00 | 2022-05-14T06:48:05.115568+00:00 | 683 | false | * For `__init__` we precompute the top voted person for each `time` in `times` in an ordered list `topVoted`.\n* For `q` we use Binary Search in `topVoted` (recycling code from <a href="https://leetcode.com/problems/search-insert-position/">35. Search Insert Position</a>) to find the top voted person at time `t`.\n\n```\nclass TopVotedCandidate:\n \n def __init__(self, persons: List[int], times: List[int]):\n self.topVoted = [0] * len(times)\n countVotes = Counter()\n currentTop = persons[0]\n \n for i, (person, time) in enumerate(zip(persons, times)):\n countVotes[person] += 1\n if countVotes[person] >= countVotes[currentTop]:\n currentTop = person\n self.topVoted[i] = (time, currentTop)\n\n def q(self, t: int) -> int:\n left, right = 0, len(self.topVoted) - 1\n \n while left <= right:\n mid = (left + right) // 2\n time, top = self.topVoted[mid]\n if time == t:\n return top\n if time < t:\n left = mid + 1\n else:\n right = mid - 1\n\n time, top = self.topVoted[right]\n return top\n``` | 4 | 0 | ['Binary Tree', 'Python'] | 2 |
online-election | C++, 240ms , Map + Count Vector, Very Easy to understand, Explanation given | c-240ms-map-count-vector-very-easy-to-un-7c6p | This question was really confusing after couple of errors I figured out the question and also it took some time to figure out perfect working solution that didn | phaninderg | NORMAL | 2021-12-23T05:11:40.386349+00:00 | 2021-12-23T05:11:40.386386+00:00 | 478 | false | This question was really confusing after couple of errors I figured out the question and also it took some time to figure out perfect working solution that didn\'t result in TLE\n\nHere is the code snipped which is very easy to understand\nThe vector inside constructor holds the count of votes of each person\ncurrentMax will always hold which person is leading at any point of time, so that we can compare only with him\nAfter every iteration update the map with time and current leading person ,so that we can refer to the map at later point of time\n\n```\nclass TopVotedCandidate {\n map<int,int> mymap;\npublic:\n TopVotedCandidate(vector<int>& persons, vector<int>& times) {\n int currentMax = persons[0];\n vector<int> voteCount(persons.size(),-1);\n for(int i=0; i<persons.size(); ++i) {\n voteCount[persons[i]]++;\n if(voteCount[persons[i]] >= voteCount[currentMax])\n currentMax = persons[i];\n mymap[times[i]] = currentMax;\n }\n }\n int q(int t) {\n auto low = mymap.lower_bound(t);\n if(low->first != t) low--;\n return low->second;\n }\n};\n```\nHope this helps someone | 4 | 0 | [] | 0 |
online-election | Anybody has a magic general formula for Binary Search? | anybody-has-a-magic-general-formula-for-seuvu | record each time, which person is leading using a hash map\n2. binary search current query time\n\nQuestion is:\nHow do you decide between\nwhile (lo <= hi) \nw | cheng_coding_attack | NORMAL | 2018-11-10T23:01:58.448807+00:00 | 2018-11-10T23:01:58.448855+00:00 | 1,354 | false | 1. record each time, which person is leading using a hash map\n2. binary search current query time\n\nQuestion is:\nHow do you decide between\n``` while (lo <= hi) ``` \n``` while (lo < hi) ```\n``` while (lo < hi - 1) ```?\nI looked at couple binary search problems, each is different when it comes to the terminal condition, I have to wrong answer and debug for a few times to get it right, it will be great if someone can provide some insight on how to choose, thanks.\n\n```\nclass TopVotedCandidate {\n \n private int[] lead;\n \n private int[] times;\n\n public TopVotedCandidate(int[] persons, int[] times) {\n this.times = times;\n int len = persons.length;\n lead = new int[len];\n int high = 0;\n int prevWin = 0;\n // person, votes\n Map<Integer, Integer> map = new HashMap<>();\n for (int i = 0; i < persons.length; i++) {\n int person = persons[i];\n map.put(person, map.getOrDefault(person, 0) + 1);\n if (map.get(person) > high) {\n high = map.get(person);\n lead[i] = person;\n prevWin = person;\n } else if (map.get(person) == high) {\n lead[i] = person;\n prevWin = person;\n } else {\n lead[i] = prevWin;\n }\n }\n }\n \n public int q(int t) {\n int lo = 0;\n int hi = times.length - 1;\n while (lo < hi) {\n int mid = (lo + hi) / 2;\n if (times[mid] == t) {\n return lead[mid];\n } else if (times[mid] > t) {\n hi = mid - 1;\n } else {\n lo = mid + 1;\n }\n }\n if (times[lo] <= t) return lead[lo];\n return lo - 1 < 0 ? -1 : lead[lo - 1];\n }\n \n}\n``` | 4 | 0 | [] | 4 |
online-election | [java] Binary search | java-binary-search-by-big_news-ltm4 | ``` class TopVotedCandidate { int[] leading; int[] time; public TopVotedCandidate(int[] persons, int[] times) { time = times; leadin | big_news | NORMAL | 2018-09-23T03:12:45.188699+00:00 | 2018-10-02T14:16:55.157868+00:00 | 959 | false | ```
class TopVotedCandidate {
int[] leading;
int[] time;
public TopVotedCandidate(int[] persons, int[] times) {
time = times;
leading = new int[persons.length];
Map<Integer, Integer> map = new HashMap<>();
for (int n : persons){
map.put(n, 0);
}
int max = persons[0];
for (int i = 0; i < times.length; i++){
if (i == 0){
map.put(persons[i], 1);
leading[i] = persons[i];
}else{
map.put(persons[i], map.get(persons[i]) + 1);
if (max != persons[i] && map.get(persons[i]) >= map.get(max)){
max = persons[i];
}
leading[i] = max;
}
//System.out.print(leading[i]);
}
}
public int q(int t) {
int i = 0, j = time.length;
while (i < j){
int mid = i + (j - i) / 2;
if (time[mid] <= t){
i = mid + 1;
}else{
j = mid;
}
}
return leading[i - 1];
}
}
``` | 4 | 0 | [] | 0 |
online-election | [C++] Easy Upper_Bound Solution | c-easy-upper_bound-solution-by-makhonya-3q28 | \nclass TopVotedCandidate {\npublic:\n unordered_map<int, int> m;\n vector<int> times;\n TopVotedCandidate(vector<int> persons, vector<int> times) {\n | makhonya | NORMAL | 2022-09-03T09:21:00.273214+00:00 | 2022-09-03T09:21:00.273253+00:00 | 814 | false | ```\nclass TopVotedCandidate {\npublic:\n unordered_map<int, int> m;\n vector<int> times;\n TopVotedCandidate(vector<int> persons, vector<int> times) {\n int n = persons.size(), lead = -1;\n this->times = times;\n unordered_map<int, int> count;\n for (int i = 0; i < n; ++i) {\n lead = ++count[persons[i]] >= count[lead] ? persons[i] : lead;\n m[times[i]] = lead;\n }\n }\n\n int q(int t) {\n return m[*--upper_bound(times.begin(), times.end(), t)];\n }\n};\n``` | 3 | 0 | ['C', 'C++'] | 0 |
online-election | ✅ || python || using hashmap + binary search || | python-using-hashmap-binary-search-by-ab-rdfq | \nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n \n \n self.leading =[]\n \n self.ti | Abhishen99 | NORMAL | 2021-07-16T17:18:02.716011+00:00 | 2021-07-16T19:46:20.459979+00:00 | 535 | false | ```\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n \n \n self.leading =[]\n \n self.times = []\n \n count = defaultdict(int)\n ma = 0\n \n for i , p in enumerate(persons):\n \n count[p]+=1\n \n if count[p]>= ma:\n \n ma= count[p]\n self.leading.append(p)\n self.times.append(times[i])\n \n \n def search(self, ar , target):\n l,r = 0,len(ar)-1\n while l<=r:\n \n mid = l+(r-l)//2\n if ar[mid] == target:\n return mid\n elif ar[mid] > target:\n r = mid-1\n else:\n l= mid+1\n return l-1\n \n \n\n def q(self, t: int) -> int:\n \n index = self.search(self.times, t)\n return self.leading[index]\n \n \n\n\n# Your TopVotedCandidate object will be instantiated and called as such:\n# obj = TopVotedCandidate(persons, times)\n# param_1 = obj.q(t)\n``` | 3 | 1 | ['Python', 'Python3'] | 0 |
online-election | Python3 precomputed + binary search | python3-precomputed-binary-search-by-red-l1tr | \nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.times = times\n self.series = [0] * len(persons | redtree1112 | NORMAL | 2019-03-25T09:10:30.429480+00:00 | 2019-03-25T09:10:30.429537+00:00 | 433 | false | ```\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.times = times\n self.series = [0] * len(persons)\n vote = [0] * len(persons)\n win = -1\n for i, time in enumerate(times):\n person = persons[i]\n vote[person] += 1\n\n if vote[person] >= win:\n self.series[i] = person\n win = vote[person]\n else:\n self.series[i] = self.series[i - 1]\n\n def q(self, t: int) -> int:\n return self.series[self.bisect_right(t, self.times) - 1]\n\n def bisect_right(self, target, nums):\n lo, hi = 0, len(nums)\n while lo < hi:\n mid = lo + (hi - lo) // 2\n if nums[mid] <= target:\n lo = mid + 1\n else:\n hi = mid\n return hi\n``` | 3 | 0 | [] | 0 |
online-election | ✅✔️Easy implementation using upper bound || C++ Solution ✈️✈️✈️✈️✈️ | easy-implementation-using-upper-bound-c-qz3mw | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ajay_1134 | NORMAL | 2023-07-23T17:35:04.588794+00:00 | 2023-07-23T17:35:04.588816+00:00 | 754 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass TopVotedCandidate {\npublic:\n vector<int>time;\n vector<int>ans;\n TopVotedCandidate(vector<int>& persons, vector<int>& times) {\n int n = persons.size();\n time = times;\n int mxp = -1;\n unordered_map<int,int>mp;\n for(int i=0; i<n; i++){\n mp[persons[i]]++;\n if(mp[persons[i]] >= mp[mxp]){\n mxp = persons[i];\n }\n ans.push_back(mxp);\n }\n }\n \n int q(int t) {\n int idx = (upper_bound(time.begin(),time.end(),t) - time.begin()) - 1;\n return ans[idx];\n }\n};\n\n/**\n * Your TopVotedCandidate object will be instantiated and called as such:\n * TopVotedCandidate* obj = new TopVotedCandidate(persons, times);\n * int param_1 = obj->q(t);\n */\n``` | 2 | 0 | ['Array', 'Hash Table', 'Binary Search', 'C++'] | 0 |
online-election | Python3 solution beats 91.11% 🚀 || quibler7 | python3-solution-beats-9111-quibler7-by-bdi7i | \n\n# Code\n\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.persons = []\n self.times = []\n | quibler7 | NORMAL | 2023-05-15T06:29:19.024449+00:00 | 2023-05-15T06:29:19.024492+00:00 | 836 | false | \n\n# Code\n```\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.persons = []\n self.times = []\n self.dic = collections.defaultdict(int)\n self.m = 0\n self.idx = -1\n\n for i in range(len(times)):\n self.times.append(times[i])\n self.dic[persons[i]] += 1\n if self.dic[persons[i]] >= self.m:\n self.persons.append(persons[i])\n self.m = self.dic[persons[i]]\n else:\n self.persons.append(self.persons[-1])\n\n def q(self, t: int) -> int:\n idx = bisect.bisect_right(self.times,t)\n return self.persons[idx-1]\n\n``` | 2 | 0 | ['Python3'] | 1 |
online-election | Solution | solution-by-deleted_user-tx4j | C++ []\nclass TopVotedCandidate {\npublic:\n TopVotedCandidate(vector<int> persons, vector<int> times) {\n int max_count = 0, candidate = 0, len = per | deleted_user | NORMAL | 2023-05-12T04:20:48.894843+00:00 | 2023-05-12T05:21:24.489752+00:00 | 971 | false | ```C++ []\nclass TopVotedCandidate {\npublic:\n TopVotedCandidate(vector<int> persons, vector<int> times) {\n int max_count = 0, candidate = 0, len = persons.size();\n int count[len + 1];\n memset(count, 0, sizeof count);\n candidates = vector<pair<int, int>>(len);\n for(int i = 0; i < len; i++){\n count[persons[i]]++;\n if(count[persons[i]] >= max_count){\n max_count = count[persons[i]];\n candidate = persons[i];\n }\n candidates[i].first = times[i];\n candidates[i].second = candidate;\n }\n }\n int q(int t) {\n int lo = 0, hi = candidates.size();\n while(lo < hi){\n int m = (lo + hi) / 2;\n if(candidates[m].first <= t){\n lo = m + 1;\n }else{\n hi = m;\n }\n }\n return candidates[lo - 1].second;\n }\nprivate:\n vector<pair<int, int>> candidates;\n };\n```\n\n```Python3 []\nclass TopVotedCandidate:\n \n def __init__(self, persons, times):\n self.leads, self.times, count = [], times, defaultdict(int)\n lead = -1\n for p in persons:\n count[p] += 1\n if count[p] >= count.get(lead, 0): lead = p\n self.leads.append(lead)\n\n def q(self, t):\n return self.leads[bisect.bisect(self.times, t) - 1]\n```\n\n```Java []\nclass TopVotedCandidate {\n private final int[] time;\n private final int[] leader;\n public TopVotedCandidate(int[] persons, int[] times) {\n LeaderChange head = new LeaderChange();\n LeaderChange tail = head;\n int n = persons.length;\n int[] votes = new int[n];\n int currentLeader = -1;\n int maxVotes = 0;\n int changeCount = 0;\n for (int i = 0; i < n; i++) {\n int p = persons[i];\n int v = ++votes[p];\n if (v >= maxVotes) {\n maxVotes = v;\n if (p != currentLeader) {\n tail = new LeaderChange(times[i], currentLeader = p, tail);\n changeCount++;\n }\n }\n }\n time = new int[changeCount];\n leader = new int[changeCount];\n for (int i = 0; i < changeCount; i++) {\n head = head.next;\n time[i] = head.time;\n leader[i] = head.leader;\n }\n }\n public int q(int t) {\n int left = 0;\n int right = time.length;\n while (true) {\n int mid = (left + right) >>> 1;\n if (mid == left)\n break;\n if (time[mid] <= t)\n left = mid;\n else\n right = mid;\n }\n return leader[left];\n }\n private static class LeaderChange {\n final int time;\n final int leader;\n LeaderChange next;\n\n LeaderChange() {\n time = 0;\n leader = 0;\n }\n LeaderChange(int time, int leader, LeaderChange previous) {\n this.time = time;\n this.leader = leader;\n previous.next = this;\n }\n }\n}\n```\n | 2 | 0 | ['C++', 'Java', 'Python3'] | 1 |
online-election | Easiest Java Solution || Binary Search on Times | easiest-java-solution-binary-search-on-t-xhpw | \n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n\nclass TopVotedCandidate {\n\n HashMap<Integer,Integer>time=new HashMap<> | jaiyadav | NORMAL | 2023-01-13T07:43:24.228256+00:00 | 2023-01-13T07:43:24.228315+00:00 | 1,601 | false | \n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass TopVotedCandidate {\n\n HashMap<Integer,Integer>time=new HashMap<>();\n\n int[]arr=null;\n\n public TopVotedCandidate(int[] persons, int[] times) {\n \n int maxi=Integer.MIN_VALUE;\n arr=times;\n HashMap<Integer,Integer>mp=new HashMap<>();\n int maxperson=0;\n for(int i=0;i<times.length;i++){\n\n if(!mp.containsKey(persons[i])){\n mp.put(persons[i],1);\n }\n else mp.put(persons[i],mp.get(persons[i])+1);\n\n if(maxi<mp.get(persons[i])){\n time.put(times[i],persons[i]);\n maxi=mp.get(persons[i]);\n maxperson=persons[i];\n }\n else if(maxi==mp.get(persons[i])){\n time.put(times[i],persons[i]);\n maxperson=persons[i];\n }\n else{\n time.put(times[i],maxperson);\n }\n }\n }\n \n public int q(int K) {\n int start = 0;\n int end = arr.length-1;\n while (start <= end) {\n int mid = (start + end) / 2;\n if (arr[mid] == K)\n return time.get(arr[mid]);\n else if (arr[mid] < K)\n start = mid + 1;\n else\n end = mid - 1;\n }\n \n return time.get(arr[end]);\n \n }\n}\n\n/**\n * Your TopVotedCandidate object will be instantiated and called as such:\n * TopVotedCandidate obj = new TopVotedCandidate(persons, times);\n * int param_1 = obj.q(t);\n */\n``` | 2 | 0 | ['Array', 'Hash Table', 'Binary Search', 'Design', 'Java'] | 1 |
online-election | Easy JS Solution | easy-js-solution-by-dollysingh-bgqg | \n# Code\n\n/**\n * @param {number[]} persons\n * @param {number[]} times\n */\nvar TopVotedCandidate = function(persons, times) {\n let maxC = 0;\n let m | dollysingh | NORMAL | 2023-01-07T17:04:30.983340+00:00 | 2023-01-07T17:04:30.983383+00:00 | 504 | false | \n# Code\n```\n/**\n * @param {number[]} persons\n * @param {number[]} times\n */\nvar TopVotedCandidate = function(persons, times) {\n let maxC = 0;\n let maxP = null;\n\n let map = new Map();\n let tmap = new Map();\n\n for(let i = 0; i < persons.length; i++) {\n let p = persons[i];\n let t = times[i];\n if(map.has(p)) {\n map.set(p, map.get(p) + 1);\n } else {\n map.set(p, 1);\n }\n let c = map.get(p);\n if(c > maxC) {\n maxC = c;\n maxP = p;\n } else if(c === maxC) {\n maxP = p; //since time is increasing\n } \n // else c < maxC, we do not want to update maxP\n tmap.set(t, maxP);\n }\n\n this.times = times;\n this.tmap = tmap;\n};\n\n/** \n * @param {number} t\n * @return {number}\n */\nTopVotedCandidate.prototype.q = function(t) {\n let low = 0;\n let high = this.times.length - 1;\n let ans = -1;\n\n while(low <= high) {\n let mid = low + Math.floor((high - low)/2);\n\n if(this.times[mid] > t) {\n high = mid - 1;\n } else {\n low = mid + 1;\n ans = mid;\n }\n }\n\n return this.tmap.get(this.times[ans]);\n};\n\n\n\n\n/** \n * Your TopVotedCandidate object will be instantiated and called as such:\n * var obj = new TopVotedCandidate(persons, times)\n * var param_1 = obj.q(t)\n */\n``` | 2 | 0 | ['Binary Search', 'JavaScript'] | 0 |
online-election | Java || Beats 90% || Complete Explanation || Binary Search | java-beats-90-complete-explanation-binar-bz7v | ```\nclass TopVotedCandidate {\n \n HashMap map = new HashMap<>();\n // declaring global arrays for the persons and times array\n int [] person;\n | kurmiamreet44 | NORMAL | 2022-12-14T07:30:53.707167+00:00 | 2022-12-14T07:30:53.707210+00:00 | 401 | false | ```\nclass TopVotedCandidate {\n \n HashMap<Integer, Integer> map = new HashMap<>();\n // declaring global arrays for the persons and times array\n int [] person;\n int [] time;\n // stores the winner at any point of time\n int [] winners;\n public TopVotedCandidate(int[] persons, int[] times) {\n person = persons;\n time = times;\n winners= new int[time.length];\n // map stores the person which comes at time t and his vote number is updated in the map\n map.put(person[0],1);\n // max is continously checking who the max is eg.like when 1 comes after zero the max is updated to 1 when the values\n // for both 0 and 1 is same and 1 is more recent, if we get a bigger value then we update or else max remains same \n // for that time\n int max = person[0];\n winners[0]=max;\n for(int i=1;i<person.length;i++)\n {\n //updating in the map\n map.put(person[i],map.getOrDefault(person[i],0)+1); \n // update the max if the condition fulfills\n if(map.get(person[i])>=map.get(max)) \n {\n max = person[i]; \n }\n // if value(votes) of the current person is greater then winner will be him, so the max would have gotten updated,\n // else winner[i] is same as winner[i-1]\n winners[i]=max;\n }\n \n }\n \n public int q(int t) {\n int low = -1;\n int high =time.length;\n // binary search to find the lower bound like for time 12, 10 is the lower bound so we check the max votes at time 10.\n while(low+1<high)\n {\n int mid = low + (high - low)/2;\n //if(time[mid]== t)\n //return winners[mid];\n if(time[mid]<=t)\n low= mid;\n else\n high = mid;\n }\n \n return winners[low];\n }\n} | 2 | 0 | ['Java'] | 0 |
online-election | Easily Understandable | easily-understandable-by-pritamsinghsola-gm2h | 1.Treemap is used to quickly serach on the times.\n2.mp_2 is used to store the ith person lead.\n3.lead is used just to maintain the lead for next time and assi | pritamsinghsolanki | NORMAL | 2022-07-06T06:28:09.147384+00:00 | 2023-05-05T05:40:12.587290+00:00 | 455 | false | 1.Treemap is used to quickly serach on the times.\n2.mp_2 is used to store the ith person lead.\n3.lead is used just to maintain the lead for next time and assign it at the right time as said in the question .\n \n```\nclass TopVotedCandidate {\n TreeMap<Integer,Integer> mp=new TreeMap<>(); \n HashMap<Integer,Integer> mp_2=new HashMap<>();\n int lead=-1;\n public TopVotedCandidate(int[] persons, int[] times) {\n for(int i=0;i<persons.length;i++){\n mp_2.put(persons[i],mp_2.getOrDefault(persons[i],0)+1);\n if(lead==-1 || mp_2.get(persons[i]) >= mp_2.get(lead)){\n lead=persons[i];\n }\n mp.put(times[i],lead);\n }\n }\n \n public int q(int t) {\n int idx = mp.floorKey(t);\n return mp.get(idx);\n }\n}\n\n/**\n * Your TopVotedCandidate object will be instantiated and called as such:\n * TopVotedCandidate obj = new TopVotedCandidate(persons, times);\n * int param_1 = obj.q(t);\n */\n ```\n upvote please if you find helpful | 2 | 0 | ['Java'] | 1 |
online-election | online election | online-election-by-ninjamonkey42-m6tk | \n#times: [0, 5, 10]\n#persons: [0, 1, 1]\n#leader: [0, 1, 1]\n#array item values represent the candidates\n#at a specific timestamp, the candidate | NinjaMonkey42 | NORMAL | 2022-06-16T10:39:38.316016+00:00 | 2022-07-11T16:22:25.244548+00:00 | 414 | false | ```\n#times: [0, 5, 10]\n#persons: [0, 1, 1]\n#leader: [0, 1, 1]\n#array item values represent the candidates\n#at a specific timestamp, the candidate was casted a vote by someone\n#each occurence of candidate in persons list represent the vote received by the candidate\n#https://leetcode.com/problems/online-election/discuss/180972/Anyone-else-just-find-this-question-really-confusing\n#votes dict would contain the votes for each candidate\n#build a leader list with winners for corresponding timestamp\n#binary search the timestamp <= query_timestamp\n#return winner at index of timestamp found\nfrom collections import defaultdict\nclass TopVotedCandidate:\n #T=O(n), S=O(n)\n def __init__(self, persons: List[int], times: List[int]):\n #class variable to make it accessible from query method\n self.times = times\n self.leader = [None]*len(persons)\n #arbitrary value for the init\n winner = -1\n #votes dict would contain votes received by each candidate\n #votes = {person1: votes, person2: votes}\n votes = defaultdict(int)\n for i, p in enumerate(persons):\n #increment the vote received by the specific candidate\n #votes = {person1: 2, person2: 6}\n votes[p] += 1\n #check if votes of current person is greater than or equal to votes received by the latest winner\n #equal to because for same vote count, we take the recent candidate\n #winner should be one of the candidates\n if votes[p] >= votes[winner]:\n #update the winner to current person\n winner = p\n #modify the leader list to current winner (person)\n #self.leader = [person1, person1, person2,...]\n self.leader[i] = winner\n \n #T=O(lgn), S=O(1)\n def q(self, t: int) -> int:\n #binary-search because time is monotonic increasing\n #search space\n #find the winner at timestamp <= query_timestamp (t)\n left, right = 0, len(self.times)\n while left < right:\n mid = left + (right-left)//2\n #final value of left would be the min that satisfies below condition\n if t < self.times[mid]:\n right = mid\n else:\n left = mid + 1\n\t\t#return the winner\n\t\t#left pointer represent the min timestamp greater than query_timestamp\n\t\t#therefore, take (left-1) to get the timestamp that equals to or lesser than query_timestamp\n return self.leader[left-1]\n\t\t\n\t\t\n\t\t\n\n#CONCISE\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.times = times\n self.leader = []\n votes = defaultdict(int)\n winner = -1\n for p in persons:\n votes[p] += 1\n if votes[p] >= votes[winner]:\n winner = p\n self.leader.append(winner)\n\n def q(self, t: int) -> int:\n l, r = 0, len(self.times)\n while l<r:\n m = l+(r-l)//2\n if t < self.times[m]:\n r = m\n else:\n l = m+1\n return self.leader[l-1]\n``` | 2 | 0 | ['Binary Tree', 'Python'] | 0 |
online-election | C++ | Segment Tree | O(log N) Query | O(Nlog N) preprocessing | c-segment-tree-olog-n-query-onlog-n-prep-c1yu | \n#define fi first\n#define se second\nusing piii = pair<pair<int,int>,int>;\nstruct SegmentTree{\n vector<piii> t;\n SegmentTree(int N){\n t.assig | shadow_47 | NORMAL | 2022-06-02T12:31:14.272839+00:00 | 2022-06-02T12:31:14.272874+00:00 | 58 | false | ```\n#define fi first\n#define se second\nusing piii = pair<pair<int,int>,int>;\nstruct SegmentTree{\n vector<piii> t;\n SegmentTree(int N){\n t.assign(4 * N + 10,{{0, -1}, 0});\n Build(0,0,N-1);\n }\n piii Combine(piii &a,piii &b){\n if(a.fi.fi!=b.fi.fi)return a.fi.fi > b.fi.fi ? a : b;\n else return a.fi.se >= b.fi.se ? a : b;\n }\n void Build(int v,int l,int r){\n if(l==r){\n t[v].se = l;\n return;\n }\n int m = l + (r-l)/2;\n Build(2*v+1,l,m);\n Build(2*v+2,m+1,r);\n t[v] = Combine(t[2*v+1],t[2*v+2]);\n }\n void Update(int v,int l,int r,int idx,int time){\n if(l==r){\n t[v].fi.fi += 1;\n t[v].fi.se = time;\n return;\n }\n int m = l + (r-l)/2;\n if(idx<=m)Update(2*v+1,l,m,idx,time);\n else Update(2*v+2,m+1,r,idx,time);\n t[v] = Combine(t[2*v+1],t[2*v+2]);\n }\n};\nclass TopVotedCandidate {\npublic:\n int N;\n vector<int> t,mx_C;\n TopVotedCandidate(vector<int>& persons, vector<int>& times) {\n N = times.size();\n t.assign(N,-1); mx_C.assign(N,-1);\n SegmentTree st(N);\n for(int i=0;i<N;i++){\n t[i] = times[i];\n st.Update(0,0,N-1,persons[i],times[i]);\n mx_C[i] = st.t[0].se;\n }\n }\n \n int q(int time) {\n int l = 0,r = N-1,idx = -1;\n while(l<=r){\n int m = l + (r-l)/2;\n if(t[m]<=time){\n idx = m;\n l = m + 1;\n }else r = m - 1;\n }\n return mx_C[idx];\n }\n};\n``` | 2 | 0 | ['Tree', 'Binary Tree'] | 0 |
online-election | [Java] simple solution using treetop | java-simple-solution-using-treetop-by-mw-f5h8 | \nclass TopVotedCandidate {\n TreeMap<Integer, Integer> tm = new TreeMap<>();\n\n // get lader for each moment in time one by one\n public TopVotedCand | mwacc | NORMAL | 2022-02-12T20:25:07.853928+00:00 | 2022-02-12T20:25:07.853972+00:00 | 127 | false | ```\nclass TopVotedCandidate {\n TreeMap<Integer, Integer> tm = new TreeMap<>();\n\n // get lader for each moment in time one by one\n public TopVotedCandidate(int[] persons, int[] times) {\n Map<Integer, Integer> votes = new HashMap<>(); // candidate -> number of votes\n int leader = -1;\n // int[] leaders = new int[persons.length];\n for(int i=0; i<persons.length; ++i) {\n int person = persons[i];\n int n = votes.getOrDefault(person, 0)+1;\n votes.put(person, n);\n if(leader==-1) {\n leader = person;\n } else if( votes.get(leader) <= n ) {\n leader = person;\n }\n tm.put(times[i], leader);\n }\n }\n \n public int q(int t) {\n var entry = tm.floorEntry(t);\n return entry.getValue();\n }\n}\n\n\n``` | 2 | 0 | ['Tree'] | 0 |
online-election | 100% faster than all C# submissions (at the time of writing) | 100-faster-than-all-c-submissions-at-the-6alq | \n public class TopVotedCandidate\n {\n private List<Vote> votes = new List<Vote>();\n\n public TopVotedCandidate(int[] persons, int[] times | mojo1234 | NORMAL | 2022-02-10T13:24:23.855960+00:00 | 2022-02-10T13:24:40.977355+00:00 | 248 | false | ```\n public class TopVotedCandidate\n {\n private List<Vote> votes = new List<Vote>();\n\n public TopVotedCandidate(int[] persons, int[] times) \n {\n var tally = new Dictionary<int, int>();\n int lastPerson = -1;\n\n for (int i = 0; i < persons.Length; i++)\n {\n var person = persons[i];\n if (!tally.ContainsKey(person))\n tally.Add(person, 0);\n tally[person] += 1;\n if (person != lastPerson && (lastPerson < 0 || tally[person] >= tally[lastPerson]))\n {\n lastPerson = persons[i];\n votes.Add(\n new Vote\n {\n Person = lastPerson,\n Time = times[i]\n }) ;\n }\n }\n }\n\n public int Q(int t)\n {\n var start = 1;\n var end = votes.Count;\n while(start <= end && start != votes.Count)\n {\n var mid = start + ((end - start) / 2);\n var vote = votes[mid];\n if (vote.Time == t)\n return vote.Person;\n else if (vote.Time > t)\n end = mid - 1;\n else\n start = mid + 1;\n }\n return votes[start - 1].Person;\n }\n }\n\n public class Vote\n {\n public int Person { get; set; }\n public int Time { get; set; }\n }\n``` | 2 | 0 | ['C#'] | 1 |
online-election | Easy to understand - TreeMap Solution || O(N + Q*log(N)) | easy-to-understand-treemap-solution-on-q-xli6 | \nclass TopVotedCandidate \n{\n //Time Complexity: O(N + Q*logN), where N is the number of votes, and Q is the number of queries.\n \n TreeMap<Integer, | dhake_baba_met17 | NORMAL | 2021-07-31T21:30:36.694483+00:00 | 2021-08-27T11:41:41.538994+00:00 | 216 | false | ```\nclass TopVotedCandidate \n{\n //Time Complexity: O(N + Q*logN), where N is the number of votes, and Q is the number of queries.\n \n TreeMap<Integer, Integer> map; // Our main Red-Black tree for searching\n HashMap<Integer, Integer> store;\n int person, maxVotes; // Stores the person who could be the answer at that time\n\n public TopVotedCandidate(int[] persons, int[] times) \n {\n this.map = new TreeMap<>();\n this.store = new HashMap<>();\n \n\t\tstore.put(persons[0], 1);\n map.put(times[0], persons[0]);\n person = persons[0];\n maxVotes = 1;\n\t\t\n for(int i=1; i<times.length; i++)\n {\n if(store.containsKey(persons[i]))\n\t\t\t\tstore.put(persons[i], 1 + store.get(persons[i]));\n else store.put(persons[i], 1);\n \n if(maxVotes<=store.get(persons[i]))\n {\n map.put(times[i], persons[i]);\n person = persons[i];\n maxVotes = store.get(persons[i]);\n }\n\t\t\telse map.put(times[i], person);\n }\n }\n \n public int q(int t) \n {\n if(!map.containsKey(t))\n t = map.lowerKey(t); // Takes O(logN) time, does lower-bound binary search\n return map.get(t);\n \n }\n}\n``` | 2 | 0 | ['Tree', 'Binary Search Tree', 'Java'] | 2 |
online-election | Python3 Binary Search with short explanation | python3-binary-search-with-short-explana-99tq | You\'re told that times is sorted, so you can already begin thinking of binary search. Now all you need to know is who is leading at what time which is why you | jsn667 | NORMAL | 2021-05-24T14:49:16.979088+00:00 | 2021-05-24T14:50:49.813214+00:00 | 168 | false | You\'re told that times is sorted, so you can already begin thinking of binary search. Now all you need to know is who is leading at what time which is why you keep count of who is leading at each index of the "times" array. Then, when you are asked to find a leader for a certain time, you binary search for the time in the "times" array to get the index and then match it with the array you precomputed to find out who is leading during that time.\n```\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.times = times\n self.leading_at_x_time = [0] * len(persons)\n counter = {}\n current_leader = -1\n most_votes = 0\n for index, person in enumerate(persons):\n counter[person] = counter.get(person, 0) + 1\n if counter[person] >= most_votes:\n most_votes = counter[person]\n current_leader = person\n self.leading_at_x_time[index] = current_leader\n\n def q(self, t: int) -> int:\n index = bisect.bisect_left(self.times, t)\n if index >= len(self.times) or self.times[index] != t:\n index -= 1\n return self.leading_at_x_time[index]\n\n\n# Your TopVotedCandidate object will be instantiated and called as such:\n# obj = TopVotedCandidate(persons, times)\n# param_1 = obj.q(t)\n``` | 2 | 0 | [] | 1 |
online-election | [Python3] binary search O(logN) for query | python3-binary-search-ologn-for-query-by-er1g | Algo\nWhile running initializer, we compute the frequency table of each candidates votes and decide winner at each time stamp. When running query, we binary sea | ye15 | NORMAL | 2020-12-01T03:41:52.658126+00:00 | 2020-12-01T03:41:52.658166+00:00 | 295 | false | **Algo**\nWhile running initializer, we compute the frequency table of each candidates votes and decide winner at each time stamp. When running query, we binary search the proper moment to decide who the winner is at that time. \n\n**Implementation**\n```\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.times = times \n self.winner = []\n \n pp = 0 \n freq = {} # frequency table \n for p in persons: \n freq[p] = 1 + freq.get(p, 0)\n if freq[p] >= freq.get(pp, 0): pp = p\n self.winner.append(pp)\n\n\n def q(self, t: int) -> int:\n """Standard last-true binary search."""\n lo, hi = -1, len(self.times)-1\n while lo < hi: \n mid = lo + hi + 1 >> 1\n if self.times[mid] <= t: lo = mid\n else: hi = mid - 1\n return self.winner[lo]\n\n\n# Your TopVotedCandidate object will be instantiated and called as such:\n# obj = TopVotedCandidate(persons, times)\n# param_1 = obj.q(t)\n```\n\n**Analysis**\nTime complexity `O(N)` for initializer `O(logN)` for query\nSpace complexity `O(N)` | 2 | 0 | ['Python3'] | 0 |
online-election | C++ | Unordered_map | Upper bound | c-unordered_map-upper-bound-by-wh0ami-idpo | \nclass TopVotedCandidate {\n unordered_map<int, int>m;\n vector<int>time;\npublic:\n TopVotedCandidate(vector<int>& persons, vector<int>& times) {\n | wh0ami | NORMAL | 2020-06-17T09:29:01.999455+00:00 | 2020-06-17T09:29:01.999484+00:00 | 110 | false | ```\nclass TopVotedCandidate {\n unordered_map<int, int>m;\n vector<int>time;\npublic:\n TopVotedCandidate(vector<int>& persons, vector<int>& times) {\n unordered_map<int, int>count;\n int lead = -1;\n time = times;\n for (int i = 0; i < persons.size(); i++) {\n count[persons[i]]++;\n if (count[persons[i]] >= count[lead])\n lead = persons[i];\n m[times[i]] = lead;\n }\n }\n \n int q(int t) {\n int val = *(--upper_bound(time.begin(), time.end(), t));\n return m[val];\n }\n};\n``` | 2 | 0 | [] | 0 |
online-election | C# Binary Search based implementation | c-binary-search-based-implementation-by-be90y | (Side note :By the time I submitted this solution it beated the existed solution 100%\nQuote: "Runtime: 696 ms, faster than 100.00% of C# online submissions for | captain_u | NORMAL | 2019-01-20T00:29:09.799270+00:00 | 2019-01-20T00:29:09.799310+00:00 | 283 | false | (Side note :By the time I submitted this solution it beated the existed solution 100%\nQuote: "Runtime: 696 ms, faster than 100.00% of C# online submissions for Online Election.")\n\n*Time Complexity:* \nFor Method ```TopVotedCandidate```: O(N) where N is the size of the times array. \nFor Method ```Q```: O(log(N)) for binary search.\n*Space Complexity:*\nO(N) where N as before.\n\nThe key insight is, at each time \'snapshot\' we need to record the top voted candidate. For that we can keep a dictinary named ```TopCandidate``` where key is the time index (i.e. it is an index of the ```times``` array corresponding to the time the snapshot is taken). \n\nI beleve I was able to achieve the best runtime (at the time of submission of this solution), because I used the in-built Array.BinarySearch in .net. \nRead the comments for additional info. \n\n```\npublic class TopVotedCandidate {\n \n IDictionary<int,int> TopCandidate; // (key - time index, value - topCandidate)\n // This \'HashMap\' is to keep the cop candidate for each time Index (not the time itself)\n \n int[] Times;\n // Keep this time as a class level ref to access in method Q\n\n public TopVotedCandidate(int[] persons, int[] times)\n {\n // Validations - DUE\n \n TopCandidate = new Dictionary<int,int>();\n Times = times;\n var VoteCounts = new Dictionary<int,int>(); // (key - candidate, value - votes)\n int topCount = 0; // Current Top Count\n int topCandidate = 0;\n for(int i = 0; i < persons.Length; i++)\n {\n if(!VoteCounts.TryAdd(persons[i],1))\n {\n VoteCounts[persons[i]]++;\n }\n \n if (VoteCounts[persons[i]] >= topCount) // The equal sign in inniquality is to keep keep the most recent result\n {\n topCount = VoteCounts[persons[i]];\n topCandidate = persons[i];\n }\n \n TopCandidate.Add(i, topCandidate);\n }\n \n }\n \n public int Q(int t)\n {\n int timeIdx = Array.BinarySearch(Times,t); // Use the in-built binary search in .net\n if (timeIdx < 0) // In case we don nott have an exact match. Read the microsoft doc for more details\n {\n timeIdx = ~timeIdx - 1; \n // timeIdx = Math.Min(timeIdx,Times.Length - 1); // In case we search a really higher time\n } \n \n return TopCandidate[timeIdx];\n }\n}\n\n/**\n * Your TopVotedCandidate object will be instantiated and called as such:\n * TopVotedCandidate obj = new TopVotedCandidate(persons, times);\n * int param_1 = obj.Q(t);\n */\n``` | 2 | 0 | [] | 0 |
online-election | [Java] TreeMap: O(NlogN) + O(logN) and Binary Search: O(N) + O(logN) | java-treemap-onlogn-ologn-and-binary-sea-ad63 | Below its standard TreeMap solution, as map.put takes O(logN) so the constructor takes O(NlogN).\n\nclass TopVotedCandidate {\n\n TreeMap<Integer, Integer> m | goku_wukong | NORMAL | 2018-10-01T06:37:11.336912+00:00 | 2018-10-01T06:42:05.852718+00:00 | 553 | false | Below its standard TreeMap solution, as map.put takes O(logN) so the constructor takes O(NlogN).\n```\nclass TopVotedCandidate {\n\n TreeMap<Integer, Integer> map = new TreeMap<>();\n public TopVotedCandidate(int[] persons, int[] times) {\n \n HashMap<Integer, Integer> count = new HashMap<>();\n int highestCount = 0, highestPerson = 0;\n\n for (int i = 0; i < persons.length; i++) {\n int person = persons[i];\n Integer current = count.get(person);\n count.put(person, current == null ? 1 : current + 1);\n\n if (count.get(person) >= highestCount) {\n highestCount = count.get(person);\n highestPerson = person;\n }\n map.put(times[i], highestPerson);\n }\n }\n \n public int q(int t) {\n return map.get(map.floorKey(t));\n }\n}\n```\n\nBelow its a better O(N) + O(logN) Binary Search solution, used array + Binary Search instead. The max[i] repersents the top candidate at times[i]. \n[Arrays.binarySearch(sorted array, key)](https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch(int[],%20int)) Return the index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1).\n```\nclass TopVotedCandidate {\n\n int[] max, times;\n public TopVotedCandidate(int[] persons, int[] times) {\n this.times = times;\n max = new int[persons.length];\n HashMap<Integer, Integer> count = new HashMap<>();\n int highestCount = 0, highestPerson = 0;\n\n for (int i = 0; i < persons.length; i++) {\n int key = persons[i];\n Integer current = count.get(key);\n count.put(key, current == null ? 1 : current + 1);\n\n if (count.get(key) >= highestCount) {\n highestCount = count.get(key);\n highestPerson = key;\n }\n max[i] = highestPerson;\n }\n }\n \n public int q(int t) {\n int timePoint = Arrays.binarySearch(times, t);\n return max[timePoint < 0 ? -timePoint - 2 : timePoint];\n }\n}\n``` | 2 | 0 | [] | 1 |
online-election | JavaScript solution | javascript-solution-by-dva2-ug6z | https://github.com/dva22/leetcode/blob/master/problems/911.%20Online%20Election/index.js\n\nvar TopVotedCandidate = module.exports = function(persons, times) { | dva2 | NORMAL | 2018-09-26T00:31:48.320237+00:00 | 2018-09-26T00:31:48.320286+00:00 | 299 | false | https://github.com/dva22/leetcode/blob/master/problems/911.%20Online%20Election/index.js\n```\nvar TopVotedCandidate = module.exports = function(persons, times) {\n this.winningTimes = {};\n this.times = times;\n var votesCount = [];\n \n var currentWinningPerson = -1;\n var winningVotes = 0;\n for (var i = 0; i < persons.length; i++) {\n if (!votesCount[persons[i]]) {\n votesCount[persons[i]] = 0;\n };\n votesCount[persons[i]]++;\n \n if (votesCount[persons[i]] >= winningVotes) {\n winningVotes = votesCount[persons[i]];\n currentWinningPerson = persons[i];\n }\n this.winningTimes[times[i]] = currentWinningPerson;\n }\n};\n\n/** \n * @param {number} t\n * @return {number}\n */\nTopVotedCandidate.prototype.q = function(t1) {\n var p = 0;\n while (this.times[p] < t1) {\n p++;\n }\n \n if (this.times[p] === t1) {\n return this.winningTimes[this.times[p]];\n }\n return this.winningTimes[this.times[p-1]];\n};\n``` | 2 | 0 | [] | 0 |
online-election | Java solution using PriorityQueue and BinarySearch (O(n*log(n)) | java-solution-using-priorityqueue-and-bi-94gd | Code | swapit | NORMAL | 2025-03-21T12:04:49.507274+00:00 | 2025-03-21T12:04:49.507274+00:00 | 50 | false | # Code
```java []
class TopVotedCandidate {
public class Candidate {
int id;
int votes;
int latestVoteIndex;
public Candidate(int id, int votes, int latestVoteIndex) {
this.id = id;
this.votes = votes;
this.latestVoteIndex = latestVoteIndex;
}
}
HashMap<Integer, Candidate> db;
PriorityQueue<Candidate> pq;
int[] topCandidates;
int[] times;
public TopVotedCandidate(int[] persons, int[] times) {
this.times = times;
this.db = new HashMap<>();
this.pq = new PriorityQueue<>(
(c1, c2) -> c1.votes == c2.votes ? c2.latestVoteIndex - c1.latestVoteIndex : c2.votes - c1.votes);
this.topCandidates = new int[persons.length];
for (int i = 0; i < persons.length; i++) {
Candidate can = db.getOrDefault(persons[i], new Candidate(persons[i], 0, 0));
pq.remove(can);
can.votes = can.votes + 1;
can.latestVoteIndex = i;
db.put(persons[i], can);
pq.add(can);
topCandidates[i] = pq.peek().id;
}
}
public int q(int t) {
int start = 0;
int end = times.length - 1;
int index = 0;
while (start <= end) {
int mid = (start + end) / 2;
if (times[mid] > t) {
end = mid - 1;
} else if (times[mid] <= t) {
start = mid + 1;
index = mid;
}
}
return topCandidates[index];
}
}
``` | 1 | 0 | ['Java'] | 0 |
online-election | ✅ 🎯 📌 Simple Solution || Dictionary || Prefix Sum || Binary Search || Fastest Solution ✅ 🎯 📌 | simple-solution-dictionary-prefix-sum-bi-mn6h | Code\npython3 []\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.persons=[]\n self.times=[]\n | vvnpais | NORMAL | 2024-09-14T19:34:09.371597+00:00 | 2024-09-14T19:34:09.371632+00:00 | 339 | false | # Code\n```python3 []\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.persons=[]\n self.times=[]\n self.d=defaultdict(int)\n self.mx=0\n for person,time in zip(persons,times):\n self.times.append(time)\n self.d[person]+=1\n if self.d[person]>=self.mx:\n self.persons.append(person)\n self.mx=self.d[person]\n else: self.persons.append(self.persons[-1])\n\n def q(self, t: int) -> int:\n return self.persons[bisect.bisect_right(self.times,t)-1]\n\n# Your TopVotedCandidate object will be instantiated and called as such:\n# obj = TopVotedCandidate(persons, times)\n# param_1 = obj.q(t)\n``` | 1 | 0 | ['Array', 'Hash Table', 'Binary Search', 'Design', 'Python3'] | 0 |
online-election | Simple python solution beats 85% of users (HashMap-BinarySearch) | simple-python-solution-beats-85-of-users-o915 | Code\n\nfrom collections import defaultdict\nimport bisect\n\nclass TopVotedCandidate:\n\n def __init__(self, persons, times):\n self.leadings = []\n | youssefkhalil320 | NORMAL | 2024-05-17T18:28:11.331704+00:00 | 2024-05-17T18:28:11.331731+00:00 | 197 | false | # Code\n```\nfrom collections import defaultdict\nimport bisect\n\nclass TopVotedCandidate:\n\n def __init__(self, persons, times):\n self.leadings = []\n self.times = times\n self.vote_counts = defaultdict(int)\n leading = -1\n \n for i in range(len(persons)):\n person = persons[i]\n time = times[i]\n self.vote_counts[person] += 1\n \n if leading == -1 or self.vote_counts[person] >= self.vote_counts[leading]:\n # If there\'s a tie or the current person has more votes, they become the new leader.\n # The "most recent vote" is handled by the order of votes coming in.\n leading = person\n \n self.leadings.append(leading)\n \n def q(self, t):\n # Binary search to find the index of the largest time <= t\n idx = bisect.bisect_right(self.times, t) - 1\n return self.leadings[idx] if idx >= 0 else None\n``` | 1 | 0 | ['Hash Table', 'Binary Search', 'Python3'] | 0 |
online-election | python3 solution beats 97% 🚀 || quibler7 | python3-solution-beats-97-quibler7-by-qu-uek6 | Code\n\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.persons = []\n self.times = []\n s | quibler7 | NORMAL | 2023-05-07T03:46:48.412533+00:00 | 2023-05-07T03:46:48.412562+00:00 | 518 | false | # Code\n```\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.persons = []\n self.times = []\n self.dic = collections.defaultdict(int)\n self.m = 0\n self.idx = -1\n\n for i in range(len(times)):\n self.times.append(times[i])\n self.dic[persons[i]] += 1\n if self.dic[persons[i]] >= self.m:\n self.persons.append(persons[i])\n self.m = self.dic[persons[i]]\n else:\n self.persons.append(self.persons[-1])\n\n def q(self, t: int) -> int:\n idx = bisect.bisect_right(self.times,t)\n return self.persons[idx-1]\n\n``` | 1 | 0 | ['Python3'] | 1 |
online-election | ✅ beats 100% Java code | beats-100-java-code-by-abstractconnoisse-eeid | Java Code\n\nclass TopVotedCandidate {\n private final int[] time;\n private final int[] leader;\n public TopVotedCandidate(int[] persons, int[] times) | abstractConnoisseurs | NORMAL | 2023-02-13T07:34:24.921300+00:00 | 2023-02-13T07:34:24.921334+00:00 | 224 | false | # Java Code\n```\nclass TopVotedCandidate {\n private final int[] time;\n private final int[] leader;\n public TopVotedCandidate(int[] persons, int[] times) {\n LeaderChange head = new LeaderChange();\n LeaderChange tail = head;\n int n = persons.length;\n int[] votes = new int[n];\n int currentLeader = -1;\n int maxVotes = 0;\n int changeCount = 0;\n for (int i = 0; i < n; i++) {\n int p = persons[i];\n int v = ++votes[p];\n if (v >= maxVotes) {\n maxVotes = v;\n if (p != currentLeader) {\n tail = new LeaderChange(times[i], currentLeader = p, tail);\n changeCount++;\n }\n }\n }\n time = new int[changeCount];\n leader = new int[changeCount];\n for (int i = 0; i < changeCount; i++) {\n head = head.next;\n time[i] = head.time;\n leader[i] = head.leader;\n }\n }\n\n public int q(int t) {\n int left = 0;\n int right = time.length;\n while (true) {\n int mid = (left + right) >>> 1;\n if (mid == left)\n break;\n if (time[mid] <= t)\n left = mid;\n else\n right = mid;\n }\n return leader[left];\n }\n\n private static class LeaderChange {\n final int time;\n final int leader;\n LeaderChange next;\n\n LeaderChange() {\n time = 0;\n leader = 0;\n }\n\n LeaderChange(int time, int leader, LeaderChange previous) {\n this.time = time;\n this.leader = leader;\n previous.next = this;\n }\n }\n}\n``` | 1 | 1 | ['Array', 'Hash Table', 'Binary Search', 'Design', 'Java'] | 0 |
online-election | C++✅ || Easy || Solution | c-easy-solution-by-prinzeop-4sfl | \nclass TopVotedCandidate {\npublic:\n map<int, int> m2;\n unordered_map<int, int> m;\n\tTopVotedCandidate(vector<int>& persons, vector<int>& times) {\n\t | casperZz | NORMAL | 2022-08-16T11:01:42.134987+00:00 | 2022-08-16T11:04:17.510195+00:00 | 664 | false | ```\nclass TopVotedCandidate {\npublic:\n map<int, int> m2;\n unordered_map<int, int> m;\n\tTopVotedCandidate(vector<int>& persons, vector<int>& times) {\n\t\tint lead = -1;\n\t\tm[-1] = 0;\n\t\tint n = persons.size();\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tm[persons[i]]++;\n\t\t\tif (m[persons[i]] >= m[lead]) lead = persons[i];\n\t\t\tm2[times[i]] = lead;\n\t\t}\n\t}\n\n\tint q(int t) {\n\t\treturn (*(--m2.upper_bound(t))).second;\n\t}\n};\n``` | 1 | 0 | ['C', 'Binary Tree'] | 0 |
online-election | Easy Solution using a HashMap and a TreeMap | easy-solution-using-a-hashmap-and-a-tree-61bn | \nclass TopVotedCandidate {\n // <key: voting candidate, value: count of votes a candidate has received>\n HashMap<Integer, Integer> voteCount;\n // <k | oori3280 | NORMAL | 2022-08-08T06:48:25.653230+00:00 | 2022-08-08T06:48:25.653263+00:00 | 264 | false | ```\nclass TopVotedCandidate {\n // <key: voting candidate, value: count of votes a candidate has received>\n HashMap<Integer, Integer> voteCount;\n // <key: timestamp, value: who is the leader with max vote>\n TreeMap<Integer, Integer> timeToLeader;\n int currentLeader;\n public TopVotedCandidate(int[] persons, int[] times) {\n voteCount = new HashMap<>();\n timeToLeader = new TreeMap<>();\n for(int i = 0; i < persons.length; i++) {\n int person = persons[i];\n int time = times[i];\n int count = voteCount.getOrDefault(person, 0) + 1;\n if(i == 0 || voteCount.get(currentLeader) <= count) {\n currentLeader = person;\n }\n voteCount.put(person, count);\n timeToLeader.put(time, currentLeader);\n }\n }\n \n public int q(int t) {\n int floorTimeStamp = timeToLeader.floorKey(t);\n return timeToLeader.get(floorTimeStamp);\n }\n}\n``` | 1 | 0 | [] | 0 |
online-election | [Python] Clean, simple with explanation | python-clean-simple-with-explanation-by-widei | \nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n counter = defaultdict(int)\n\n mostVotePersons = [0] | npq | NORMAL | 2022-07-22T15:34:11.075381+00:00 | 2022-07-22T15:34:11.075418+00:00 | 322 | false | ```\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n counter = defaultdict(int)\n\n mostVotePersons = [0] * len(persons) # mostVotePersons[i] is the most vote person at times[i]\n largestVote = -1 # keep largest vote person index\n for i in range(len(persons)):\n counter[persons[i]] += 1\n if largestVote == -1 or counter[persons[i]] >= counter[largestVote]:\n largestVote = persons[i]\n mostVotePersons[i] = largestVote\n \n self.times = times\n self.mostVotePersons = mostVotePersons\n\n def q(self, t: int) -> int:\n idx = bisect_right(self.times, t) - 1 # binary search on times to find the most recent time before t\n return self.mostVotePersons[idx]\n``` | 1 | 0 | ['Binary Tree', 'Python'] | 0 |
online-election | [Python 3] Binary Search | python-3-binary-search-by-gabhay-hlk7 | We first Precompute all winners at a given time if the winner is not changed we don\'t consider to add it to our list of winners at a given time. after that we | gabhay | NORMAL | 2022-07-07T13:56:15.512248+00:00 | 2022-07-07T13:56:15.512287+00:00 | 135 | false | We first Precompute all winners at a given time if the winner is not changed we don\'t consider to add it to our list of winners at a given time. after that we will find the lower bound of the time for which we are querying and just provide the result from our precomputed list.\nO(N)-- to precompute\nO(log(N)--> to query\ntotal complexity--O(N+q*log(N))\n\t\n\t\n\tclass TopVotedCandidate:\n\t\tdef __init__(self, p: List[int], times: List[int]):\n\n\t\t\ta=Counter()\n\t\t\tmax_vote=0\n\t\t\tself.lead=[]\n\t\t\tfor i,x in enumerate(times):\n\t\t\t\ta[p[i]]+=1\n\t\t\t\tif a[p[i]]>=max_vote:\n\t\t\t\t\tmax_vote=a[p[i]]\n\t\t\t\t\tself.lead.append([x,p[i]])\n\n\t\tdef q(self, t: int) -> int:\n\t\t\tl=0\n\t\t\tr=len(self.lead)-1\n\t\t\twhile l<=r:\n\t\t\t\tmid=l+(r-l)//2\n\t\t\t\tif self.lead[mid][0]<=t:\n\t\t\t\t\tres=mid\n\t\t\t\t\tl=mid+1\n\t\t\t\telse:\n\t\t\t\t\tr=mid-1\n\t\t\treturn self.lead[res][1] | 1 | 0 | ['Binary Search'] | 0 |
online-election | C++ SOLUTION | c-solution-by-kunal_patil-dctc | \n unordered_map mp;\n map chk;\n vector times1;\n int maxi=0;\n int ele;\n \n int binser(int k)\n {\n int i = 0;\n int j | kunal_patil | NORMAL | 2022-05-31T08:53:42.411838+00:00 | 2022-05-31T08:53:42.411877+00:00 | 104 | false | \n unordered_map<int,int> mp;\n map<int,int> chk;\n vector<int> times1;\n int maxi=0;\n int ele;\n \n int binser(int k)\n {\n int i = 0;\n int j = times1.size()-1;\n \n while(i<=j)\n {\n int mid = (i+j)/2;\n if(times1[mid]==k)\n {\n return times1[mid];\n }\n else if(times1[mid]<k)\n {\n i = mid+1;\n }\n else\n {\n j = mid-1;\n }\n }\n \n return times1[j];\n }\n\n \n TopVotedCandidate(vector<int>& persons, vector<int>& times) {\n for(int i=0;i<persons.size();i++)\n {\n chk[persons[i]]++;\n if(chk[persons[i]]>=maxi)\n {\n maxi = chk[persons[i]];\n ele = persons[i];\n }\n mp[times[i]]=ele;\n }\n times1 = times;\n }\n \n \n int q(int t) {\n int k = binser(t);\n //cout<<k<<" ";\n return mp[k];\n }\n | 1 | 0 | ['Binary Tree'] | 0 |
online-election | (C++) 911. Online Election | c-911-online-election-by-qeetcode-ezgu | \n\nclass TopVotedCandidate {\n vector<int> times, lead; \npublic:\n TopVotedCandidate(vector<int>& persons, vector<int>& times) : times(times) {\n | qeetcode | NORMAL | 2021-12-10T20:30:10.545470+00:00 | 2021-12-10T20:30:10.545520+00:00 | 300 | false | \n```\nclass TopVotedCandidate {\n vector<int> times, lead; \npublic:\n TopVotedCandidate(vector<int>& persons, vector<int>& times) : times(times) {\n unordered_map<int, int> freq; \n int pp = 0; \n for (auto& p : persons) {\n ++freq[p]; \n if (freq[p] >= freq[pp]) pp = p; \n lead.push_back(pp);\n }\n }\n \n int q(int t) {\n int k = upper_bound(times.begin(), times.end(), t) - times.begin();\n return lead[k-1]; \n }\n};\n``` | 1 | 0 | ['C'] | 1 |
online-election | Precompute + Binary Search [Java] | precompute-binary-search-java-by-itkan-p3cl | \nimport java.util.HashMap;\n\npublic class TopVotedCandidate {\n int[] winners;\n int[] times;\n\n public TopVotedCandidate(int[] persons, int[] times | itkan | NORMAL | 2021-11-20T09:52:31.374601+00:00 | 2021-11-20T09:52:31.374638+00:00 | 187 | false | ```\nimport java.util.HashMap;\n\npublic class TopVotedCandidate {\n int[] winners;\n int[] times;\n\n public TopVotedCandidate(int[] persons, int[] times) {\n this.times = times;\n winners = new int[times.length];\n\n HashMap<Integer, Integer> voteMap = new HashMap<>();\n int maxVoteCandidate = -1;\n int maxVote = 0;\n\n for (int i = 0 ; i < times.length ; i++) {\n int candidate = persons[i];\n int cumulativeVote = voteMap.merge(candidate, 1, Integer::sum);\n\n if (maxVote <= cumulativeVote) {\n maxVoteCandidate = candidate;\n maxVote = cumulativeVote;\n }\n\n winners[i] = maxVoteCandidate;\n }\n }\n\n public int q(int t) {\n int low =0,high = times.length-1,ans=-1;\n while(low<=high){\n int mid = (low+high)/2;\n if(times[mid]<=t){\n ans = Math.max(ans,mid);\n low = mid+1;\n } else{\n high = mid-1;\n }\n }\n return winners[ans];\n }\n}\n``` | 1 | 0 | ['Binary Tree', 'Java'] | 0 |
online-election | 📌📌 Easy and Well Explained || 98% faster || Simple Approach 🐍 | easy-and-well-explained-98-faster-simple-z78h | IDEA :\nIn the order of time, we count the number of votes for each person.\nAlso, we update the current lead of votes for each time point.\nif (count[person] | abhi9Rai | NORMAL | 2021-11-06T14:36:21.442661+00:00 | 2021-11-06T14:36:21.442690+00:00 | 118 | false | ## IDEA :\nIn the order of time, we count the number of votes for each person.\nAlso, we update the current lead of votes for each time point.\n`if (count[person] >= count[lead]) lead = person`\n\nTime Complexity: O(N)\n\n**Implementation :**\n\n\'\'\'\n\n\tclass TopVotedCandidate:\n def __init__(self, persons: List[int], times: List[int]):\n self.leads, self.dic, self.times = [], defaultdict(int), times\n lead = -1\n for p in persons:\n self.dic[p]+=1\n if self.dic[p]>=self.dic[lead]:\n lead = p\n self.leads.append(lead)\n \n def q(self, t: int) -> int:\n ind = bisect.bisect_left(self.times,t)\n if ind>=len(self.times) or self.times[ind] != t:\n ind-=1\n return self.leads[ind]\n \n **Thanks and Upvote if you like the Idea !!\uD83E\uDD1E** | 1 | 0 | [] | 0 |
online-election | Pre-computation + Binary Search [C++] | pre-computation-binary-search-c-by-siddh-7wmq | \n unordered_map<int, int> mp;\n vector<int> pref, times;\n int best = -1;\n \n TopVotedCandidate(vector<int>& persons, vector<int>& times) {\n | siddhantchimankar | NORMAL | 2021-11-04T13:52:36.978078+00:00 | 2021-11-04T13:52:36.978107+00:00 | 86 | false | ```\n unordered_map<int, int> mp;\n vector<int> pref, times;\n int best = -1;\n \n TopVotedCandidate(vector<int>& persons, vector<int>& times) {\n \n pref = vector<int>(persons.begin(), persons.end());\n this->times = times;\n \n for(int i = 0 ; i < times.size() ; i++) {\n \n mp[persons[i]]++;\n if(best == -1 || mp[persons[i]] >= mp[best]) best = persons[i];\n pref[i] = best;\n }\n }\n \n int q(int t) {\n\n auto idx = upper_bound(times.begin(), times.end(), t) - times.begin();\n if(idx == times.size()) return pref.back();\n if(times[idx] == t) return pref[idx];\n return pref[--idx];\n }\n``` | 1 | 0 | [] | 0 |
online-election | ✔️ C# - Simple to understand With Comments. Map & Binary Search | c-simple-to-understand-with-comments-map-t682 | Thumbs up if you find this helpful \uD83D\uDC4D\n\nThe main idea in this solution is to create a result array called leaders that keeps track of who the current | keperkjr | NORMAL | 2021-09-30T07:19:50.645429+00:00 | 2021-09-30T07:40:47.120428+00:00 | 99 | false | **Thumbs up if you find this helpful** \uD83D\uDC4D\n\nThe main idea in this solution is to create a result array called ```leaders``` that keeps track of who the current leader is up to that point, for each ```time[i]```.\n\nFor example:\n```\nleaders[i] = The current leading vote getter up to the point of time[i]\n```\n\nThen in the ```Q``` query function, we search the ```time``` array to get the index that matches query ```t```, and then use that index to get the leading vote getter for that time from our pre populated leaders result array\n\n```\npublic class TopVotedCandidate {\n private int[] leaders;\n private int[] times;\n \n public TopVotedCandidate(int[] persons, int[] times) {\n this.times = times;\n leaders = new int[persons.Length];\n \n var candidates = new Dictionary<int, int>();\n var leader = int.MinValue;\n var leaderVotes = int.MinValue;\n \n // Determine the leader for each time[index] and save them to an array\n for (int index = 0; index < persons.Length; ++index) {\n var person = persons[index];\n if (!candidates.ContainsKey(person)) {\n candidates[person] = 0;\n }\n var votes = candidates[person] + 1;\n if (votes >= leaderVotes) {\n leader = person;\n leaderVotes = votes;\n }\n candidates[person] = votes;\n leaders[index] = leader;\n }\n }\n \n public int Q(int t) {\n // Get the time[index] matching the search time\n var index = Search(t);\n return leaders[index];\n }\n \n private int Search(int t) {\n var lo = 0;\n var hi = times.Length -1;\n var result = -1;\n \n while (lo <= hi) {\n var m = lo + (hi - lo) / 2;\n var value = times[m];\n if (value == t) {\n result = m;\n break;\n } else if (value < t) {\n lo = m + 1;\n result = m;\n } else {\n hi = m - 1;\n }\n }\n \n return result;\n } \n}\n\n/**\n * Your TopVotedCandidate object will be instantiated and called as such:\n * TopVotedCandidate obj = new TopVotedCandidate(persons, times);\n * int param_1 = obj.Q(t);\n */\n ``` | 1 | 0 | ['Binary Tree'] | 0 |
online-election | C++ || Map || binary search | c-map-binary-search-by-priyanka1230-xqks | \n\npublic:\n mapmp;\n vector>v;\n TopVotedCandidate(vector& p, vector& times) {\n int maxx=0,curr=0;\n for(int i=0;i=maxx)\n | priyanka1230 | NORMAL | 2021-09-29T12:48:24.580399+00:00 | 2021-09-29T12:48:24.580425+00:00 | 82 | false | ```\n\n```public:\n map<int,int>mp;\n vector<pair<int,int>>v;\n TopVotedCandidate(vector<int>& p, vector<int>& times) {\n int maxx=0,curr=0;\n for(int i=0;i<p.size();i++)\n {\n mp[p[i]]++;\n if(mp[p[i]]>=maxx)\n {\n maxx=mp[p[i]];\n curr=p[i];\n }\n v.push_back({times[i],curr});\n }\n }\n \n int q(int t) {\n int i=0,ans=0;\n int l=0;\n int r=v.size()-1;\n while(l<=r)\n {\n int mid=(l+r)/2;\n if(v[mid].first<=t)\n {\n ans=v[mid].second;\n l=mid+1;\n }\n else\n {\n r=mid-1;\n }\n }\n return ans;\n }\n};\n\n\n/**\n * Your TopVotedCandidate object will be instantiated and called as such:\n * TopVotedCandidate* obj = new TopVotedCandidate(persons, times);\n * int param_1 = obj->q(t);\n */ | 1 | 0 | [] | 0 |
online-election | C# BinarySearch | c-binarysearch-by-nick_l-4dho | \npublic class TopVotedCandidate\n{\n private static int[] _top;\n private static int[] _times;\n \n public TopVotedCandidate(int[] persons, int[] t | nick_l | NORMAL | 2021-07-19T15:42:49.437905+00:00 | 2021-07-19T15:42:49.437935+00:00 | 77 | false | ```\npublic class TopVotedCandidate\n{\n private static int[] _top;\n private static int[] _times;\n \n public TopVotedCandidate(int[] persons, int[] times)\n {\n _times = times;\n _top = new int[persons.Length];\n \n var map = new Dictionary<int, int>();\n var winner = -1;\n var winnerScore = 0;\n \n for(var i = 0; i < persons.Length; i++)\n {\n var person = persons[i];\n var score = map.GetValueOrDefault(person) + 1;\n map[person] = score;\n \n if(score >= winnerScore)\n {\n winner = person;\n winnerScore = score;\n }\n \n _top[i] = winner;\n }\n \n }\n \n public int Q(int t)\n {\n var good = 0;\n var bad = _times.Length;\n \n while(bad - good > 1)\n {\n var mid = good + (bad-good)/2;\n if(_times[mid] <= t) good = mid;\n else bad = mid;\n }\n \n return _top[good];\n }\n}\n``` | 1 | 0 | [] | 0 |
online-election | C++, Probably the easiest to understand, Binary Search for querying | c-probably-the-easiest-to-understand-bin-2uxo | Precomputing the maximum voted person at each possible timestep, and performing binary search on time to find the correct time. \n\nclass TopVotedCandidate {\np | aditya_trips | NORMAL | 2021-05-30T12:20:11.324841+00:00 | 2021-05-30T12:20:11.324884+00:00 | 237 | false | Precomputing the maximum voted person at each possible timestep, and performing binary search on time to find the correct time. \n```\nclass TopVotedCandidate {\npublic:\n vector<int> persons, times,topVoted;\n TopVotedCandidate(vector<int>& p, vector<int>& t) {\n persons = p; \n times = t; \n int n = times.size();\n topVoted = vector<int> (n);\n unordered_map<int,int >mp ;\n int res = -1 ;\n int max = 0; \n for(int i=0; i<n; i++){\n mp[persons[i]] ++;\n if(mp[persons[i]] >= max) {\n max = mp[persons[i]]; \n res = persons[i]; \n }\n topVoted[i] = res; \n }\n }\n \n int q(int t) {\n int it = lower_bound(times.begin(), times.end(), t )- times.begin(); \n if(it == times.size()) return topVoted[times.size()-1]; \n if(times[it]== t){\n return topVoted[it]; \n }\n return topVoted[it-1]; \n }\n};\n``` | 1 | 0 | ['C'] | 0 |
online-election | Easy and simple solution by using map | easy-and-simple-solution-by-using-map-by-m6hp | class TopVotedCandidate {\n vectorp;\n vectort;\n vectorres;\n int sum=0;\npublic:\n TopVotedCandidate(vector& persons, vector& times) {\n | bhoomi12356789 | NORMAL | 2021-05-05T20:24:40.485542+00:00 | 2021-05-05T20:24:40.485582+00:00 | 88 | false | class TopVotedCandidate {\n vector<int>p;\n vector<int>t;\n vector<int>res;\n int sum=0;\npublic:\n TopVotedCandidate(vector<int>& persons, vector<int>& times) {\n p=persons;\n t=times;\n unordered_map<int,int>mp;\n int mx=0,mval=-1;;\n for(int i=0;i<p.size();i++)\n {\n mp[p[i]]++;\n if(mp[p[i]]>=mx)\n {\n res.push_back(p[i]);\n mx=mp[p[i]];\n mval=p[i];\n }\n else\n {\n res.push_back(mval);\n }\n }\n }\n \n int q(int y) {\n int x=lower_bound(t.begin(),t.end(),y)-t.begin();\n if(x==0 && t[0]>y)\n {\n return 0;\n }\n if(x==t.size())\n {\n return res[t.size()-1];\n }\n cout<<x<<"-> ";\n if(t[x]!=y)\n {\n x--;\n }\n cout<<x<<" ";\n return res[x];\n }\n}; | 1 | 2 | ['C'] | 0 |
online-election | JavaScript Solution - Binary Search Approach | javascript-solution-binary-search-approa-flei | \nvar TopVotedCandidate = function(persons, times) {\n this.times = times;\n this.len = times.length;\n this.votes = new Array(this.len).fill(0);\n | Deadication | NORMAL | 2021-03-22T17:16:46.188029+00:00 | 2021-03-22T17:19:07.280598+00:00 | 220 | false | ```\nvar TopVotedCandidate = function(persons, times) {\n this.times = times;\n this.len = times.length;\n this.votes = new Array(this.len).fill(0);\n \n let max = 0; // max votes received by any single candidate so far.\n let leader = -1l;\n \n this.leaders = persons.map((person, i) => {\n this.votes[person]++;\n \n if (this.votes[person] >= max) {\n max = this.votes[person];\n leader = person;\n }\n \n return leader;\n });\n \n};\n\nTopVotedCandidate.prototype.q = function(t) {\n let left = 0;\n let right = this.len - 1;\n \n while (left <= right) {\n const mid = left + Math.floor((right - left) / 2);\n \n if (this.times[mid] === t) return this.leaders[mid];\n else if (this.times[mid] < t) left = mid + 1;\n else right = mid - 1;\n }\n\t\n return this.leaders[right];\n};\n``` | 1 | 0 | ['Binary Tree', 'JavaScript'] | 0 |
online-election | Java Using HashMap And TreeMap | java-using-hashmap-and-treemap-by-tara-9-s0rs | The question is quite simple.We just have to find which person is leading at a given time\n\nclass TopVotedCandidate {\n Map<Integer,Integer> voteCount = new | tara-97 | NORMAL | 2021-01-12T06:06:33.132294+00:00 | 2021-01-12T06:06:33.132329+00:00 | 101 | false | The question is quite simple.We just have to find which person is leading at a given time\n```\nclass TopVotedCandidate {\n Map<Integer,Integer> voteCount = new HashMap<>();\n TreeMap<Integer,Integer> lead = new TreeMap<>();\n int maxVotes = 0;\n public TopVotedCandidate(int[] persons, int[] times) {\n int n = persons.length;\n for(int i=0;i<n;i++){\n int votes = voteCount.getOrDefault(persons[i],0);\n votes++;\n voteCount.put(persons[i],votes);\n if(maxVotes <= votes){\n maxVotes = votes;\n lead.put(times[i],persons[i]);\n }\n \n }\n \n }\n \n public int q(int t) {\n return lead.floorEntry(t).getValue();\n \n }\n}\n\n``` | 1 | 0 | [] | 0 |
online-election | C++ simple precompute and then query | c-simple-precompute-and-then-query-by-yo-zonk | \nclass TopVotedCandidate {\npublic:\n array<int,5001> votes = {};\n map<int,int> time2winner;\n \n TopVotedCandidate(vector<int>& persons, vector<in | youngkobe | NORMAL | 2021-01-02T21:16:15.409216+00:00 | 2021-01-02T21:16:15.409260+00:00 | 98 | false | ```\nclass TopVotedCandidate {\npublic:\n array<int,5001> votes = {};\n map<int,int> time2winner;\n \n TopVotedCandidate(vector<int>& persons, vector<int>& times) {\n if(persons.empty())\n return;\n int currentWinner = persons[0];\n time2winner[times[0]] = currentWinner;\n votes[currentWinner]++;\n for(int i =1;i<persons.size(); ++i)\n {\n int voted = persons[i];\n int time = times[i];\n int res = ++votes[voted];\n if(res >= votes[currentWinner])\n currentWinner = voted;\n time2winner[times[i]] = currentWinner;\n }\n }\n \n int q(int t) {\n return prev(time2winner.upper_bound(t))->second;\n }\n};\n``` | 1 | 0 | [] | 0 |
online-election | Simple Java Solution using TreeMap | simple-java-solution-using-treemap-by-mi-7719 | \nclass TopVotedCandidate {\n // Space is O(N)\n TreeMap<Integer, Integer> timeMaxVoteMap = new TreeMap<>();\n // 5000 is based on the limits provided | milind9179367800 | NORMAL | 2020-12-26T08:31:03.838628+00:00 | 2020-12-26T08:31:03.838678+00:00 | 203 | false | ```\nclass TopVotedCandidate {\n // Space is O(N)\n TreeMap<Integer, Integer> timeMaxVoteMap = new TreeMap<>();\n // 5000 is based on the limits provided in the question.\n int[] votes = new int[5000];\n int maxVotePerson = -1;\n int maxVote = 0;\n public TopVotedCandidate(int[] persons, int[] times) {\n // Over all : Nlog(n)\n for(int i = 0; i < persons.length; i++) {\n votes[persons[i]]++;\n if(votes[persons[i]] >= maxVote) {\n maxVote = votes[persons[i]];\n maxVotePerson = persons[i];\n }\n // log(N);\n timeMaxVoteMap.put(times[i], maxVotePerson);\n }\n }\n \n public int q(int t) {\n // Log(N)\n return timeMaxVoteMap.get(timeMaxVote.floorKey(t));\n }\n}\n\n/**\n * Your TopVotedCandidate object will be instantiated and called as such:\n * TopVotedCandidate obj = new TopVotedCandidate(persons, times);\n * int param_1 = obj.q(t);\n */\n``` | 1 | 0 | ['Tree', 'Java'] | 1 |
online-election | Java easy to understand binary search | java-easy-to-understand-binary-search-by-9ugz | ```\nclass TopVotedCandidate {\n int[] persons;\n int[] times;\n\n public TopVotedCandidate(int[] persons, int[] times) {\n int max = persons[0] | zmz999 | NORMAL | 2020-10-24T07:16:32.143825+00:00 | 2020-10-24T07:16:32.143860+00:00 | 112 | false | ```\nclass TopVotedCandidate {\n int[] persons;\n int[] times;\n\n public TopVotedCandidate(int[] persons, int[] times) {\n int max = persons[0];\n Map<Integer, Integer> map = new HashMap<>();\n for (int i = 0; i < times.length; i++) {\n int count = map.getOrDefault(persons[i], 0) + 1;\n map.put(persons[i], count);\n \n if (map.get(persons[i]) >= map.get(max)) {\n max = persons[i];\n }\n persons[i] = max;\n }\n this.persons = persons;\n this.times = times;\n }\n \n public int q(int t) {\n int left = 0;\n int right = times.length - 1;\n \n while (left < right) {\n int mid = left + (right - left) / 2;\n if (times[mid] < t) {\n left = mid + 1;\n } else {\n right = mid;\n }\n }\n \n if (left - 1 >= 0 && times[left] > t) {\n left--;\n }\n \n return persons[left];\n }\n}\n | 1 | 0 | [] | 0 |
online-election | Python 3 | Binary Search + Hash Table | Explanations | python-3-binary-search-hash-table-explan-18qt | Explanation\n- For binary search problem we often need hash table for help\n- Given persion and times, we can form a time-series data, which store the informati | idontknoooo | NORMAL | 2020-09-11T00:57:58.859791+00:00 | 2020-09-11T00:57:58.859833+00:00 | 403 | false | ### Explanation\n- For binary search problem we often need hash table for help\n- Given `persion` and `times`, we can form a time-series data, which store the information indicates who\'s winning at time `t`\n\t- `times` is already an increasing series, but we need to know who\'s winning at these time points\n\t- `vote_count`: count votes for each person as time goes along\n\t- `self.time_winning`: A dictionary recording `{time: winning_person}`\n- When querying, use a binary search on `self.time` and return the cooresponding winner at that time\n\t- note that we want to use `bisect_right`, winner information is always depending on the previous time point\n### Implementation\n```\nclass TopVotedCandidate:\n def __init__(self, persons: List[int], times: List[int]):\n self.time_winning = collections.defaultdict(lambda: -1)\n vote_count = collections.defaultdict(int)\n cur_max, cur_win = 0, -1\n for p, t in zip(persons, times):\n vote_count[p] += 1\n if vote_count[p] >= cur_max: cur_max, cur_win = vote_count[p], p\n self.time_winning[t] = cur_win\n self.times = times \n\n def q(self, t: int) -> int:\n return self.time_winning[self.times[bisect.bisect_right(self.times, t)-1]]\n``` | 1 | 0 | ['Hash Table', 'Binary Search', 'Python', 'Python3'] | 0 |
online-election | C++ DP+Hash solution | c-dphash-solution-by-rom111-0lzq | \nclass TopVotedCandidate {\npublic:\n unordered_map<int,int>freq;\n unordered_map<int,int>votes;\n vector<int>ans;\n int maxi=INT_MIN;\n int a;\ | rom111 | NORMAL | 2020-08-09T17:35:26.712896+00:00 | 2020-08-09T17:35:26.712931+00:00 | 74 | false | ```\nclass TopVotedCandidate {\npublic:\n unordered_map<int,int>freq;\n unordered_map<int,int>votes;\n vector<int>ans;\n int maxi=INT_MIN;\n int a;\n TopVotedCandidate(vector<int>& persons, vector<int>& times) {\n a=0;\n for(int i=0;i<times.size();i++){\n a=max(a,times[i]);\n votes[times[i]]=persons[i];\n }\n ans=vector<int>(a+1);\n for(int i=0;i<=a;i++){\n if(votes.find(i)!=votes.end()){\n freq[votes[i]]++;\n if(freq[votes[i]]>=maxi){\n ans[i]=votes[i];\n maxi=freq[votes[i]];\n }else{\n ans[i]=ans[i-1];\n }\n }else{\n if(i==0){\n ans[i]=0;\n }else{\n ans[i]=ans[i-1];\n }\n } \n }\n }\n \n int q(int t) {\n if(t>a){\n return ans[a];\n }\n return ans[t];\n }\n};\n\n/**\n * Your TopVotedCandidate object will be instantiated and called as such:\n * TopVotedCandidate* obj = new TopVotedCandidate(persons, times);\n * int param_1 = obj->q(t);\n */\n``` | 1 | 0 | [] | 0 |
online-election | [C++] 100% faster | c-100-faster-by-kangchunhung-4ork | \nclass TopVotedCandidate {\npublic:\n int *votes, *timestamp, last_time;\n TopVotedCandidate(vector<int>& persons, vector<int>& times) {\n ios_bas | kangchunhung | NORMAL | 2020-07-16T08:33:23.541398+00:00 | 2020-07-16T08:33:23.541440+00:00 | 119 | false | ```\nclass TopVotedCandidate {\npublic:\n int *votes, *timestamp, last_time;\n TopVotedCandidate(vector<int>& persons, vector<int>& times) {\n ios_base::sync_with_stdio(0);\n cin.tie(0); cout.tie(0);\n last_time = times.back() + 1;\n int L = persons.size();\n votes = new int[L];\n timestamp = new int[last_time];\n for(int i = 0; i < L; i++){\n votes[i] = 0;\n }\n int winner_now = 0;\n int ts = 0;\n for(int i = 0; i < last_time; i++){\n if(i == times[ts] && ts < L){\n votes[persons[ts]]++;\n if(votes[persons[ts]] >= votes[winner_now])\n winner_now = persons[ts];\n timestamp[i] = winner_now;\n ts++;\n }else{\n timestamp[i] = winner_now;\n }\n }\n // for(int i = 0; i < times.back(); i++){\n // cout << i << " : " << timestamp[i] << "\\n";\n // }\n }\n \n int q(int t) {\n if(t >= last_time)\n return timestamp[last_time - 1];\n return timestamp[t];\n }\n};\n\n/**\n * Your TopVotedCandidate object will be instantiated and called as such:\n * TopVotedCandidate* obj = new TopVotedCandidate(persons, times);\n * int param_1 = obj->q(t);\n */\n``` | 1 | 0 | [] | 0 |
online-election | Python Clean Solution | python-clean-solution-by-olivia_xie_93-a1bm | python\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.nums = []\n count = collections.Counter() | olivia_xie_93 | NORMAL | 2020-07-05T03:32:44.325040+00:00 | 2020-07-05T03:32:44.325076+00:00 | 106 | false | ```python\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.nums = []\n count = collections.Counter()\n mx = 0\n major = None\n \n for people, time in zip(persons, times):\n count[people] += 1\n if count[people] >= mx:\n mx = count[people]\n if major != people:\n major = people\n self.nums.append([time, major])\n\n def q(self, t: int) -> int:\n target = t+1\n start, end = 0, len(self.nums)-1\n while start+1 < end:\n mid = start+(end-start)//2\n if self.nums[mid][0] < target:\n start = mid\n else:\n end = mid\n if self.nums[end][0] < target:\n return self.nums[end][1]\n if self.nums[start][0] < target:\n return self.nums[start][1]\n return -1\n\n# Your TopVotedCandidate object will be instantiated and called as such:\n# obj = TopVotedCandidate(persons, times)\n# param_1 = obj.q(t)\n``` | 1 | 0 | [] | 0 |
online-election | Python3 dict look up or array binary search - Online Election | python3-dict-look-up-or-array-binary-sea-1kfq | \nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.times = times\n self.winner = {times[0]: person | r0bertz | NORMAL | 2020-07-01T03:13:47.024067+00:00 | 2020-07-01T03:14:06.294853+00:00 | 259 | false | ```\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.times = times\n self.winner = {times[0]: persons[0]}\n c = Counter({persons[0]: 1})\n maxCount = 1\n for i in range(1, len(times)):\n p = persons[i]\n c[p] += 1\n if c[p] >= maxCount:\n maxCount = c[p]\n self.winner[times[i]] = p\n else:\n self.winner[times[i]] = self.winner[times[i-1]] \n\n def q(self, t: int) -> int:\n if t in self.winner:\n return self.winner[t]\n i = bisect.bisect(self.times, t)\n return self.winner[self.times[i-1]]\n``` | 1 | 0 | ['Binary Search', 'Python', 'Python3'] | 0 |
online-election | O(N) + O(QLogN) | on-oqlogn-by-shivam529-qjih | \nclass TopVotedCandidate {\n int []leaders;\n int []times;\n public TopVotedCandidate(int[] persons, int[] times) {\n leaders=new int[persons.l | shivam529 | NORMAL | 2020-05-24T20:45:14.902053+00:00 | 2020-05-24T20:45:14.902107+00:00 | 108 | false | ```\nclass TopVotedCandidate {\n int []leaders;\n int []times;\n public TopVotedCandidate(int[] persons, int[] times) {\n leaders=new int[persons.length];\n this.times=times;\n Map<Integer,Integer> map=new HashMap<>();\n int leader=-1;\n int max=-1;\n for(int i=0;i<persons.length;i++){\n map.put(persons[i],map.getOrDefault(persons[i],0)+1);\n if(map.get(persons[i])>=max){\n max=map.get(persons[i]);\n leader=persons[i];\n }\n leaders[i]=leader;\n }\n \n }\n \n public int q(int t) {\n int lo=0;\n int hi=times.length-1;\n while(lo<hi){\n int mid=lo+(hi-lo+1)/2;\n if(times[mid]<=t) lo=mid;\n else hi=mid-1;\n \n }\n return leaders[lo];\n \n }\n}\n\n/**\n * Your TopVotedCandidate object will be instantiated and called as such:\n * TopVotedCandidate obj = new TopVotedCandidate(persons, times);\n * int param_1 = obj.q(t);\n */\n ``` | 1 | 0 | ['Java'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.