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
maximum-frequency-after-subarray-operation
Beats 100% Java
beats-100-java-by-alansuncomet2-06jv
IntuitionProblem basically is trying to find the largest subarray of one specific element - the number of ks in the subarray.ApproachReminded me of Kadanes with
alansuncomet2
NORMAL
2025-01-26T04:31:21.409227+00:00
2025-01-26T04:31:21.409227+00:00
207
false
# Intuition Problem basically is trying to find the largest subarray of one specific element - the number of ks in the subarray. # Approach Reminded me of Kadanes with a counting approach. # Complexity - Time complexity: O(n) - Space complexity: O(1) # Code ```java [] class Solution { public int maxFrequency(int[] nums, int k) { int max = 0; int[][] tracker = new int[50][3]; int targets = 0; for (int i = 0; i < nums.length; i++) { int num = nums[i] - 1; if (nums[i] == k) { targets++; for (int j = 0; j < 50; j++) { if (tracker[j][0] < i) { tracker[j][2]--; } } continue; } if (tracker[num][2] <= 0) { tracker[num][0] = i; tracker[num][2] = 1; tracker[num][1] = Math.max(tracker[num][2], tracker[num][1]); } else { tracker[num][2]++; tracker[num][1] = Math.max(tracker[num][2], tracker[num][1]); } } for (int[] track : tracker) { max = Math.max(track[1], max); } return max + targets; } } ```
2
0
['Greedy', 'Java']
0
maximum-frequency-after-subarray-operation
Maximum Subarray Sum
maximum-subarray-sum-by-wanderingcicada-ug9v
IntuitionTry every number other than k.For example, if k = 2 and we have [1, 2, 2, 2, 1, 1, 2, 1, 3, 3, 3], try to turn 1s into 2 and try to turn 3's into 2Appr
wanderingCicada
NORMAL
2025-01-26T04:16:06.316443+00:00
2025-01-26T04:16:06.316443+00:00
230
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Try every number other than k. For example, if k = 2 and we have [1, 2, 2, 2, 1, 1, 2, 1, 3, 3, 3], try to turn 1s into 2 and try to turn 3's into 2 # Approach <!-- Describe your approach to solving the problem. --> What is the problem of simply turning all 1's in to 2's or all 3's into 2's in the example above? The problem is that there may be some k values we also turn into non-k. Example again: k = 2 nums = [1, 2, 2, 2, 1, 1, 2, 1, 3, 3, 3] Turning all 1's into 2 means turning 4 of the 2's into 3, so we would only end up with 4 2's (gain 4 1's, lose 4 2's). Therefore, it's clearly not optimal to turn all the 1's into 2. How do we calculate the optimal net gain when we choose a number to turn into k then? Well, in this example, we have 1 1, then 3 2's, then 2 1's, then 1 2, then 1 1. Turning a 1 into 2 nets us 1, turning 2's into 3 nets us -1, so really, we can model it into a subarray sum question: "What is the best subarray we can pick to maximize the sum of the following?": [1, -3, 2, -1, 1] Then do some O(n) implementation of a maximum subarray sum. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n * m) where m is the number of distinct numbers (or brute force the range). - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def maxFrequency(self, nums: List[int], k: int) -> int: kCount = sum([1 if num == k else 0 for num in nums]) ans = 0 def subArraySum(arr): @cache def best(index, started): if index >= len(arr): return 0 if started: return max(0, arr[index] + best(index + 1, True)) else: return max(arr[index] + best(index + 1, True), best(index + 1, False)) return best(0, False) for i in range(1, 51): arr = [] currI = 0 if i == k: continue for num in nums: if num == i: if currI < 0: arr.append(currI) currI = 0 currI += 1 elif num == k: if currI > 0: arr.append(currI) currI = 0 currI -= 1 if currI != 0: arr.append(currI) maxNet = subArraySum(arr) # print(i, maxNet, kCount) ans = max(ans, kCount + maxNet) return ans ```
2
0
['Python3']
0
maximum-frequency-after-subarray-operation
Using HashMap to try all numbers
using-hashmap-to-try-all-numbers-by-minh-y18a
IntuitionApproachComplexity Time complexity: Space complexity: Code
minh_nhut
NORMAL
2025-01-26T04:05:52.347140+00:00
2025-01-26T04:05:52.347140+00:00
581
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int maxFrequency(int[] nums, int k) { int numK = 0; for (int num : nums) { if (num == k) { numK++; } } Set<Integer> m = new HashSet<>(); for (int num : nums) { if (num != k) { m.add(num); } } if (m.isEmpty()) { return numK; } int maxDiff = Integer.MIN_VALUE; for (int v : m) { int[] transformed = new int[nums.length]; for (int i = 0; i < nums.length; i++) { if (nums[i] == v) { transformed[i] = 1; } else if (nums[i] == k) { transformed[i] = -1; } else { transformed[i] = 0; } } int currentMax = transformed[0]; int maxSub = currentMax; for (int i = 1; i < transformed.length; i++) { currentMax = Math.max(transformed[i], currentMax + transformed[i]); maxSub = Math.max(maxSub, currentMax); } maxDiff = Math.max(maxDiff, maxSub); } return numK + maxDiff; } } ```
2
0
['Java']
2
maximum-frequency-after-subarray-operation
Easy Javascript Solution || Beats 100% || Simple Explanation Provided || Leetcode Contest 434 ||
easy-javascript-solution-beats-100-simpl-r4yt
IntuitionThe code calculates the maximum possible frequency of the number k after applying an optimal shift value x to the elements of nums[]. It finds the maxi
Abhyanand_Sharma
NORMAL
2025-01-26T04:05:21.017807+00:00
2025-01-26T04:24:28.956527+00:00
181
false
# Intuition The code calculates the maximum possible frequency of the number `k` after applying an optimal shift value `x` to the elements of `nums[]`. It finds the maximum gain in frequency by adjusting each element and evaluates the best possible shift.<!-- Describe your first thoughts on how to solve this problem. --> # Approach Here’s the approach to solving the problem in 7 steps with emojis: 1. **🔢 Count Initial Frequency** Calculate the initial frequency of "k" in the array "nums[]" using the "filter" method to count how many times "k" appears. 2. **💡 Initialize Maximum Gain** Set a variable "maxGain" to 0, which will track the best possible gain in the frequency of "k" after shifting elements. 3. **🔄 Loop Through Shift Values** Iterate through all possible shift values "x" from -49 to 49 (inclusive), considering each value as a potential adjustment to the elements. 4. **🔄 Iterate Through Array** For each shift value "x", loop through the "nums[]" array to calculate the potential change in frequency for each element based on the shift. 5. **➕ Calculate Gain for Each Shift** For each number, calculate the value "val", which is +1 if the number after shifting equals "k" and -1 if the number was originally "k". Track the gain using a running sum. 6. **📈 Track Maximum Gain** Update "currentMax" with the best gain for each shift value, and update "maxGain" if a higher gain is found during the loop. 7. **➕ Return Result** Return the sum of the original frequency of "k" and the best possible gain found during the iterations.<!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n).<!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1).<!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] var maxFrequency = function(nums, k) { const originalCount = nums.filter(num => num === k).length; let maxGain = 0; for (let x = -49; x <= 49; x++) { let currentSum = 0; let currentMax = 0; for (const num of nums) { const val = (num + x === k ? 1 : 0) - (num === k ? 1 : 0); currentSum = Math.max(val, currentSum + val); currentMax = Math.max(currentMax, currentSum); } maxGain = Math.max(maxGain, currentMax); } return originalCount + maxGain; }; ```
2
0
['Array', 'Hash Table', 'Dynamic Programming', 'Greedy', 'Prefix Sum', 'JavaScript']
3
maximum-frequency-after-subarray-operation
[Python3] max diff
python3-max-diff-by-ye15-skja
IntuitionApproachComplexity Time complexity: Space complexity: Code
ye15
NORMAL
2025-01-26T04:03:27.070435+00:00
2025-01-26T04:03:27.070435+00:00
302
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def maxFrequency(self, nums: List[int], k: int) -> int: prefix = [0] for x in nums: prefix.append(prefix[-1]) if x == k: prefix[-1] += 1 ans = 0 for v in range(1, 51): sk = sv = most = 0 for i, x in reversed(list(enumerate(nums))): if x == k: sk += 1 elif x == v: sv += 1 most = max(most, sk - sv) ans = max(ans, sv + most + prefix[i]) return ans ```
2
0
['Python3']
0
maximum-frequency-after-subarray-operation
Kadane's like wise
kadanes-like-wise-by-sohailalamx-h9bi
Intuitionkadane's algoApproachComplexity Time complexity: O(n*50) Space complexity: O(n*50) Code
sohailalamx
NORMAL
2025-02-01T18:19:25.693264+00:00
2025-02-01T18:19:25.693264+00:00
22
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> kadane's algo # Approach <!-- Describe your approach to solving the problem. --> - divide the given array into chuncks dividers are the position of kl - keep the frequency of 1 to 50 in between ks - take each element and perform kadanes 1. if sum == 0 it means a fresh start 2. if sum > 0 it means it is carring from the previos so use sum-- because there is k (imaginary) between to adjacen cell of the frq vector - finally add the frq of k; # Complexity - Time complexity: O(n*50) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n*50) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int n = nums.size(); vector<vector<int>> frq(51, vector<int>(1, 0)); int frqK = 0; for (int x: nums) { if (x == k) { for (int i = 1; i <= 50; i++) { frq[i].push_back(0); } frqK++; } else { frq[x].back()++; } } int maxPossible = 0; // cout << "frqK: " << frqK << endl; for (int i=1; i <= 50; i++) { if(i == k) continue; vector<int>& v = frq[i]; int sum = 0; // cout << i << " -> " ; for (int x:v) { if(sum > 0) sum--; sum += x; // cout << sum << " "; maxPossible = max(maxPossible, sum); } // cout << endl; } // cout << endl << "maax: " << maxPossible << endl; // for(vector<int> &v:frq) { // for(int x: v) { // cout << x << " "; // } // cout << endl; // } return maxPossible + frqK; } }; ```
1
0
['C++']
0
maximum-frequency-after-subarray-operation
Single Pass Java Solution | Beats 100%
java-beats-100-by-samyu1997-tcd6
IntuitionTo solve this problem, we need to understand the effect of converting a value in a subarray to k. Specifically, converting a given value in a subarray
samyu1997
NORMAL
2025-01-31T07:49:12.470193+00:00
2025-01-31T08:01:23.624113+00:00
13
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> To solve this problem, we need to understand the effect of converting a value in a subarray to k. Specifically, converting a given value in a subarray to k means all occurrences of k in that subarray will be transformed into a different value. To visualize the problem, consider the following test cases: 10 2 2 **10** 2 2 2 10 10 2 with k = 10 1 &nbsp;&nbsp;2 3&nbsp;&nbsp;4&nbsp;&nbsp;4 &nbsp;5 6&nbsp;&nbsp;7 &nbsp;&nbsp;8 &nbsp;&nbsp;7 &nbsp;&nbsp;&nbsp;&nbsp; => max_freq at each point 2 2 **10 10 10 10** 2 2 2 2 with k = 10 1 2&nbsp;&nbsp;3 &nbsp;&nbsp;&nbsp;4 &nbsp;&nbsp;5 &nbsp;&nbsp;&nbsp;6&nbsp;&nbsp;5 6 7 8 &nbsp;&nbsp;&nbsp;&nbsp; => max_freq at each point At each index, we determine the maximum frequency of k that can be achieved by converting the current value. This conversion can either extend a previous occurrence of the same value (forming a contiguous subarray) or start a new conversion sequence from the current index. Extending a previous occurrence means we exclude all k's that appear after the last occurrence of this value and build on the prior frequency. Starting a new conversion means we consider all k's encountered so far, treating the current index as the beginning of a fresh sequence. For example, in the first test case, at index 4, the maximum frequency of k for the previous occurrence of 2 (at index 2) is greater than the number of 10s that follow. This suggests that extending the previous occurrence is more beneficial. In contrast, in the second test case, at index 6, the number of 10s encountered so far exceeds the maximum frequency of k from the prior occurrence of 2 (at index 1). In this case, starting a new conversion sequence from index 6 leads to a higher frequency of k. # Approach <!-- Describe your approach to solving the problem. --> The above intuition gives an approach, at each value we take the: max(maximum frequency of k at previous occurence of value, number of k's encountered so far) + 1. The 1 for the value being converted to k. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1) # Code ```java [] class Solution { public int maxFrequency(int[] nums, int k) { int max = 0, ck = 0; int[] prefix = new int[51]; for(int i = 0; i < nums.length; i++) { if(nums[i] == k) { ck++; prefix[k] = max + 1; } else { prefix[nums[i]] = Math.max(prefix[nums[i]], ck) + 1; } max = Math.max(max, prefix[nums[i]]); } return max; } } ```
1
0
['Array', 'Hash Table', 'Dynamic Programming', 'Greedy', 'Java']
1
maximum-frequency-after-subarray-operation
[C++]
c-by-bora_marian-ac30
The testcase that helped: [1, 3, 1, 9, 9, 4, 1] and k = 1 -> should output 5: explanation we take all the elements equals to 1 and then for [3, 5] we add -8. We
bora_marian
NORMAL
2025-01-29T20:23:57.730276+00:00
2025-01-29T20:23:57.730276+00:00
45
false
The testcase that helped: - [1, 3, 1, 9, 9, 4, 1] and k = 1 -> should output 5: explanation we take all the elements equals to 1 and then for [3, 5] we add -8. - We can explore the idea that we need other elements and see how they contribute to existing frequency of k. If we take 9 as example: we make the elements of nums[i] == k to be -1 and nums[i] == 9 to be 1, by computing the subarray with the maximum sum we determine how much 9 can contribute to the frequency of 1. The array we compute the subarray with the maximum sum looks like : -1, 0, -1, 1, 1, 0, -1 -> the maximum subarray sum is 2. # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { unordered_map<int, int> freq; int result = 0, sz = nums.size(); for (int i = 0; i < sz; i++) { freq[nums[i]]++; } for (auto [val, cnt] : freq) { result = max(result, calculateSum(nums, k, val)); } return result + freq[k]; } int calculateSum(vector<int>& nums, int k, int val) { int csum = 0, minsum = 0, maxsum = 0; for (int i = 0; i < nums.size(); i++) { csum += (nums[i] == val); csum -= (nums[i] == k); maxsum = max(maxsum, csum - minsum); minsum = min(minsum, csum); } return maxsum; } }; ```
1
0
['C++']
0
maximum-frequency-after-subarray-operation
tabular dp on each possible x
tabular-dp-on-each-possible-x-by-joshuad-z97h
Intuitionstatus: 0, 1, 2 0 -> we havent taken a subarray yet => we can either continue without taking or decide to take it from this index.1 -> we are currently
joshuadlima
NORMAL
2025-01-28T12:59:01.759374+00:00
2025-01-28T13:10:10.886810+00:00
22
false
# Intuition status: 0, 1, 2 0 -> we havent taken a subarray yet => we can either continue without taking or decide to take it from this index. 1 -> we are currently taking a subarray => we can either continue taking the subarray or stop taking it. 2 -> we have completed the subarray => we can only go on since only one subarray is allowed. # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n * 100 * 3) - Space complexity: O(n * 100 * 3) # Code ```cpp [] int dp[100001][3][101]; class Solution { public: int tabular(int ix, int status, int x, int k, vector<int>& nums) { for(int i = nums.size(); i >= 0; i--) { for(int j = 2; j >= 0; j--) { if(i == nums.size()) dp[i][j][x + 50] = 0; else if(j == 0) dp[i][j][x + 50] = max((nums[i] + x == k) + dp[i + 1][1][x + 50], (nums[i] == k) + dp[i + 1][0][x + 50]); else if(j == 1) dp[i][j][x + 50] = max((nums[i] + x == k) + dp[i + 1][1][x + 50], (nums[i] == k) + dp[i + 1][2][x + 50]); else dp[i][j][x + 50] = (nums[i] == k) + dp[i + 1][2][x + 50]; } } return dp[ix][status][x + 50]; } int maxFrequency(vector<int>& nums, int k) { int mn = INT_MAX, mx = INT_MIN; for(auto it : nums) mn = min(mn, it), mx = max(mx, it); int ans = 0; for(int x = k - mx; x <= k - mn; x++) { ans = max(ans, tabular(0, 0, x, k, nums)); } return ans; } }; ```
1
0
['C++']
0
maximum-frequency-after-subarray-operation
I laugh at all those mention Kadane and having a O(nm) solution. This is really O(n) DP.
i-laugh-at-all-those-mention-kadane-and-nmjnm
IntuitionTried to using template is sometimes good but it limit your creativity.This is simply O(n) DP, no loopping through 1-50. The numbers can be in any rang
leokan
NORMAL
2025-01-27T02:28:54.774863+00:00
2025-01-27T02:28:54.774863+00:00
73
false
# Intuition Tried to using template is sometimes good but it limit your creativity. This is simply O(n) DP, no loopping through 1-50. The numbers can be in any range it doesn't matter. We are really finding the array nums[i..j] with most number occurancy plus most of k outside of this range. # Approach let $$f(i) = max_{j \in j <= i} \{ count\ k\ in\ nums[0..j-1] + max\ occurance\ of\ numbers\ in\ nums[j..i]\}$$ We have $$f(i) = max(count\ k\ in\ nums[0..i-1] + 1, f(j) + 1)$$ where $$nums[j] = nums[i]$$ # Complexity - Time complexity: $$O(n)$$ with only 1 loop. - Space complexity: $$O(n)$$ # Code ```python3 [] class Solution: def maxFrequency(self, nums: List[int], k: int) -> int: count_k = [0] for num in nums: count_k.append(count_k[-1] + int(num == k)) total_k = count_k[-1] f = [0] * len(nums) prev_idx = {} ans = 0 for i, num in enumerate(nums): f[i] = 1 + count_k[i] if num in prev_idx and 1 + f[prev_idx[num]] > f[i]: f[i] = 1 + f[prev_idx[num]] prev_idx[num] = i ans = max(ans, f[i] + total_k - count_k[i+1]) return ans ```
1
0
['Python3']
1
maximum-frequency-after-subarray-operation
Fastest there is✅0ms || 100% || optimized🔥💯🚀
fastest-there-is0ms-100-optimized-by-zab-ws7a
Complexity : Time complexity: O(n) Space complexity: $O(1) Code :
zabakha
NORMAL
2025-01-26T20:55:06.824590+00:00
2025-01-26T20:55:06.824590+00:00
27
false
![image.png](https://assets.leetcode.com/users/images/f0a51db3-f2df-4729-a110-fb518b839adb_1737924889.5715954.png) --- # Complexity : - Time complexity: $O(n)$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> --- # Code : ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int f[51] = {0}; int res = 0, curr = 0; for(auto &x : nums) { f[x] = max(f[x], curr) + 1; if(x == k) { ++res; ++curr; } res = max(res, f[x]); } return res; } }; ```
1
0
['Counting', 'C++']
0
maximum-frequency-after-subarray-operation
[Python3] Max Frequency Diff with explanation
python3-max-diff-with-explanation-by-ked-1ov0
IntuitionThe original solution is from https://leetcode.com/problems/maximum-frequency-after-subarray-operation/solutions/6329906/simplest-python-solution-o-50-
keda626new
NORMAL
2025-01-26T17:01:12.374817+00:00
2025-01-26T17:07:00.641137+00:00
54
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The original solution is from https://leetcode.com/problems/maximum-frequency-after-subarray-operation/solutions/6329906/simplest-python-solution-o-50-n-try-all-numbers-only/ Thanks to @112115046 for sharing it. The basic idea is to find a subarray, that replace the **MOST COMMON** element inside with `k`, so the total number of k in the whole array becomes the number of `k` to the left/right of this subarray plus the frequency of the most common element. Or in other words, the count of `k` in the array plus the difference of the frequency between the most common element and `k` inside this subarray. # Approach <!-- Describe your approach to solving the problem. --> The explanation is kind of verbose as it describes how I interpreted the original answer. But the code is way more cleaner if you want to jump to it directly. The first step should be count the number of `k` inside the array -> This is the minimum frequency we can get. Since we will replace the most common element inside the subarray with `k`, the `k` inside this subarray will become non-k number (if `k` is not the most common one). Therefore, the difference of their frequencies is what we can gain from this subarray -> `ans = count + diff`. So the goal is to find the maximum diff among all the subarrays. Next, since the number is only ranged from 1 to 50, we could try all of them. In other words, count the difference of frequency between `k` and `x` at each position, and find the maximum one. People may wonder: what should we do when the difference becomes negative at some point? Short answer - throw the previous subarray away and reset difference to 0. When the difference <= 0, it means the `k` is the most common element in the previous subarray, and there's no way to replace **other** number to get more `k` other than doing nothing. In this scenario, we should start with the next subarray and count the diff from 0 again. A simple example, `subarray = [1,1,1,5,5,5], k=5, x=1`, while we're iterating the 1's, the diff is increasing and we keep updating the `max_diff`, until the last 1. As we iterate the following 5's, the diff decreases from 3 to 0 eventually. That tells 2 things: 1) we could replace all 1's with 5's so we can get 3 more 5's. 2) Or we can look at the next subarray to find if there's a difference greater than 3. Lastly, we would get a maximum diff for each number we tried and the final answer would be the global maximum diff across all the numbers plus the original count of k. # Complexity - Time complexity: O(50*N) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def maxFrequency(self, nums: List[int], k: int) -> int: total_count = nums.count(k) max_diff = 0 for target in range(1, 51): if target == k: continue # find the frequency difference of `target` and `k` at each index diff = 0 for num in nums: if num == target: diff += 1 elif num == k: diff -= 1 if diff < 0: # reset diff = 0 else: max_diff = max(max_diff, diff) return total_count + max_diff ```
1
0
['Python3']
0
maximum-frequency-after-subarray-operation
Kadane O(n) Soln || Commented Code
kadane-on-soln-commented-code-by-ammar-a-tbch
Complexity Time complexity: O(n) Space complexity: O(1) Code
ammar-a-khan
NORMAL
2025-01-26T16:23:15.142052+00:00
2025-01-26T16:23:15.142052+00:00
83
false
# Complexity - Time complexity: $O(n)$ - Space complexity: $O(1)$ # Code ```cpp int maxFrequency(vector<int> &nums, int k){ int kFreq = 0; //stores net freq of k for (int i = 0; i < nums.size(); ++i){ if (nums[i] == k){ ++kFreq; } } int maxFreq = 0; //stores maxFreq found for (int val = 1; val <= 50; ++val){ //all val->k & k->!k in segment //kadane's algo to find segment with max freq int currFreq = 0; for (int i = 0; i < nums.size(); ++i){ if (nums[i] != k && nums[i] != val){ continue; } currFreq += (nums[i] == k) ? -1 : 1; if (currFreq < 0){ currFreq = 0; } maxFreq = max(maxFreq, currFreq); } } return kFreq + maxFreq; } ```
1
0
['Counting', 'C++']
0
maximum-frequency-after-subarray-operation
Beginner friendly soln.
beginner-friendly-soln-by-peeyush_thakur-bfpd
IntuitionApproachComplexity Time complexity: O(50*N) Space complexity:O(N) Code
peeyush_thakur
NORMAL
2025-01-26T12:15:57.212028+00:00
2025-01-26T12:15:57.212028+00:00
85
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(50*N) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(N) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int n=nums.size(); int res=0; //Since the numbers can range from [1 to 50], so we can just try all the numbers // to see which num can give the maximum result. for(int num=1;num<=50;num++){ vector<int>v(n+1); //each index i of vector v will store the max achievable count of ks till i, //if we convert occurences of num (till index i) to k int count_k=0,count_num=0; int ks_till_now=0; for(int i=0;i<n;i++){ count_k+=(nums[i]==k); count_num+=(nums[i]==num); if(count_num<=count_k ){ //When the freq. of num and k is equal, we know that converting // the num to k till this point is not adding any benefit, so we //reset the count of num and k to 0, to compare the numbers lying ahead only. ks_till_now+=count_k; count_k=0;count_num=0; } v[i]=ks_till_now+count_num; } count_k=0,count_num=0; //Running the below for loop to count the occurences of k lying towards the right portion for(int i=n-1;i>=0;i--){ res=max(res,v[i]+count_k); count_k+=(nums[i]==k); } } return res; } }; ```
1
0
['C++']
0
maximum-frequency-after-subarray-operation
Simple Solution
simple-solution-by-prince_kumar1-9am7
IntuitionApproachComplexity Time complexity: Space complexity: Code
prince_kumar1
NORMAL
2025-01-26T11:46:37.947018+00:00
2025-01-26T11:46:37.947018+00:00
24
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int maxFrequency(int[] nums, int k) { int total = 0; for (int i=0;i<nums.length;i++) { if (nums[i] == k) { total++; } } List<Integer> nerbalithy = new ArrayList<>(); for (int num : nums) { nerbalithy.add(num); } int m = 0; for (int i = 1; i <= 50; i++) { if (i == k) continue; int x = k - i; int cSum = 0; int lx = 0; for (int j=0;j<nums.length;j++) { if (nums[j] == i) { cSum += 1; } else if (nums[j] == k) { cSum -= 1; } if (cSum < 0) { cSum = 0; } if (cSum > lx) { lx = cSum; } } if (lx > m) { m = lx; } } return total+m; } } ```
1
0
['Java']
0
maximum-frequency-after-subarray-operation
soution using kadan's algorithm with Time complaity-->O(n) space complaxity-->O(1)
soution-using-kadans-algorithm-with-time-bckx
IntuitionThe intuition is straightforward: we need to find the maximum frequency of k by performing one operation on a subarray. This can be efficiently achieve
Nikhil-error
NORMAL
2025-01-26T11:26:26.737788+00:00
2025-01-29T08:56:39.960040+00:00
60
false
# Intuition The intuition is straightforward: we need to find the maximum frequency of k by performing one operation on a subarray. This can be efficiently achieved using Kadane's algorithm... # Approach First, we count the occurrences of in the given array. Since the constraints ensure 1<=nums[i]<=50 we can iterate through each possible digit(To optimize, we can use a map to store the distinct digits present in the array and iterate only over those.) For each digit i, we treat k as -1 and i as 1 and than simplay finding maximum subarray sum using kadane's algorithm... # Complexity - Time complexity: O(50xn)=O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(50)=O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { private: int kadan(vector<int>nums,int k,int s){ int curr=0; int maxi=0; for(int i=0;i<nums.size();i++){ if(nums[i]==k)curr--; else if(nums[i]==s)curr++; maxi=max(maxi,curr); if(curr<0)curr=0; } return max(curr,maxi); } public: int maxFrequency(vector<int>& nums, int k) { int pre=count(nums.begin(),nums.end(),k); int ans=pre; for(int i=1;i<51;i++){ if(i==k)continue; int cur=kadan(nums,k,i); ans=max(ans,pre+cur); } return ans; } }; ```
1
0
['C++']
0
maximum-frequency-after-subarray-operation
Kadane's Algorithm
kadanes-algorithm-by-varun_cns-qhaq
Summary of the Algorithm's Purpose The algorithm is designed to find the maximum frequency of any element in the array after performing up to k increment operat
varun_cns
NORMAL
2025-01-26T11:22:25.713889+00:00
2025-01-26T11:22:25.713889+00:00
20
false
# Summary of the Algorithm's Purpose - The algorithm is designed to find the maximum frequency of any element in the array after performing up to k increment operations on subarrays. - It iterates over possible target values (1 to 50), calculates how many times a subarray can be converted into that value by applying the allowed operations, and tracks the maximum frequency. - The value k is treated specially by counting its existing occurrences in the array to ensure they’re factored into the result. # Code ```python [] class Solution(object): def maxFrequency(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ nums_k=nums.count(k) current=[0]*3 for val in range(1, 51): if val == k: continue current[0]=current[1]=0 for num in nums: if num == val: current[0] += 1 elif num == k: current[0] -= 1 current[0] = max(current[0], 0) current[1] = max(current[1], current[0]) current[2] = max(current[2], current[1]) current[2]+=nums_k return current[2] ```
1
0
['Python']
0
maximum-frequency-after-subarray-operation
PLEASE UPVOTE THE SOLUTION
please-upvote-the-solution-by-sojwalvilh-7r3j
Intuitionfind the largest freq of target element in range 1-50ApproachKadanes Algo for all the possible target in range 1-50Complexity Time complexity: O(50n)
the-Code-Monk
NORMAL
2025-01-26T07:58:36.709761+00:00
2025-01-26T07:58:36.709761+00:00
15
false
# Intuition find the largest freq of target element in range 1-50 # Approach Kadanes Algo for all the possible target in range 1-50 # Complexity - Time complexity: O(50n) - Space complexity: O(1) # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int k_s = 0; for(auto &i : nums) if(i == k) k_s++; int max_sub_sum = 0; for(int target = 1 ; target<=50 ; ++target) { if(target == k) continue; int max_sub_sum_target = 0; int currSum = 0; for(auto &i : nums) { if(i == target) { currSum += 1; } else if(i == k) { currSum -= 1; } if(currSum < 0) { currSum = 0; } max_sub_sum_target = max(max_sub_sum_target , currSum); } max_sub_sum = max(max_sub_sum , max_sub_sum_target); } return k_s + max_sub_sum; } }; ```
1
0
['C++']
0
maximum-frequency-after-subarray-operation
KADANE's ALGO
kadanes-algo-by-sourav19-zdof
IntuitionApproachComplexity Time complexity:O(N*K) Space complexity:O(N*K) Code
Sourav19
NORMAL
2025-01-26T06:43:11.634459+00:00
2025-01-26T06:43:11.634459+00:00
21
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity:O(N*K) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(N*K) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int n = nums.size() ; int maxFreq = 1; vector<vector<int>>freq(n+1, vector<int>(51, 0)) ; for(int i=0 ; i<n ; i++) { for(int e=1 ; e<=50 ; e++) { freq[i+1][e] = freq[i][e] + (nums[i] == e) ; } } for(int e=1 ; e<=50 ; e++) { if(e==k) continue ; int maxChange=0, change=0, start=-1, end=-1 ; pair<int,int>ans = {n,-1} ; for(int i=0 ; i<n ; i++) { if(nums[i] == e) { if(change == 0) start = i ; change++ ; } else if(nums[i] == k) change-- ; if(change > maxChange) { maxChange = change ; end = i ; ans = {start, end} ; } if(change < 0) change = 0 ; } start = ans.first ; end = ans.second ; int equalToK = 0 ; int equalToE = 0 ; if(end != -1) { equalToE = freq[end+1][e] - freq[start][e] ; equalToK = (freq[start][k] - freq[0][k]) + (freq[n][k] - freq[end][k]) ; } else { equalToK = freq[n][k] ; } maxFreq = max(maxFreq, equalToK+equalToE) ; } return maxFreq ; } }; ```
1
0
['C++']
0
maximum-frequency-after-subarray-operation
Easy to understand memoised DP code
easy-to-understand-memoised-dp-code-by-h-ezqo
IntuitionHow is this a DP problem? Well, we have to find the maximum frequency of the element k given that we are allowed to modify a subarray by adding or subt
harshsri1602
NORMAL
2025-01-26T05:57:57.228949+00:00
2025-01-26T05:57:57.228949+00:00
231
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> How is this a DP problem? Well, we have to find the maximum frequency of the element k given that we are allowed to modify a subarray by adding or subtracting a constant number. So , we will have to try this out with all possible subarrays. Since we have to go through "all" possible subarrays , we use recursion , and hence it is a DP problem. # Approach <!-- Describe your approach to solving the problem. --> Variables used : i : index we are currently at flag1 : initally set to zero , this will tell the constant number that we have to add or subtract in a subarray in order to make most of the elements in the subarray as k. (note that values of array range between 1 to 50 , so flag1=0 would mean that we havent choosen a subarray yet , otherwise we set the value of flag1 as a nums[i], which would mean that we would like to add/subtract flag1 from each value in the subarray to try to get k until flag2 is set). flag2 : This is set when we are done choosen the subarray. This means that if the subarray we choose ranged from index i to j (both inclusive) , then flag2 will be set from index j+1 onwards , which would mean "We have choosen a subarray , now just count number of occurence of k in the original array from index j+1 to n-1 , n being the size of the array) The recursion just makes sure that all the possibilies are tried. # Complexity - Time complexity: O (N * 52 * 2) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(N * 52 * 2) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int k; int dp[100000+5][52][2]; int f(int i,int flag1,int flag2,vector<int>& nums){ if(i == nums.size()) return 0; if(dp[i][flag1][flag2]!=-1) return dp[i][flag1][flag2]; int no_op=0,op=0; if(!flag1 or flag2){ if(nums[i]==k){ no_op = 1+f(i+1,flag1,flag2,nums); } else{ no_op = f(i+1,flag1,flag2,nums); } } if(!flag1 and !flag2){ op = max(1+f(i+1,nums[i],0,nums),1+f(i+1,nums[i],1,nums)); } else if(flag1 and !flag2){ if(nums[i]==flag1){ op=max(1+f(i+1,flag1,0,nums),1+f(i+1,flag1,1,nums)); } else{ op=max(f(i+1,flag1,0,nums),f(i+1,flag1,1,nums)); } } return dp[i][flag1][flag2]=max(no_op,op); } int maxFrequency(vector<int>& nums, int har) { k=har; int n = nums.size(); memset(dp,-1,sizeof(dp)); return f(0,0,0,nums); } }; ```
1
0
['Dynamic Programming', 'C++']
1
maximum-frequency-after-subarray-operation
SLIDING WINDOW || SIMPLEST
sliding-window-simplest-by-shivbh321-d4hp
Intuitionso if nums[i] == 50 and k==1 so u have to subtract 49 and if nums[i]==1 and k==50 so you have to add 49 that's why from -50 to 50Approachcount the ini
shivbh321
NORMAL
2025-01-26T05:46:23.005880+00:00
2025-01-26T05:46:23.005880+00:00
183
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> What can be the value of x? only from -50 to 50 but why? because nums contains values from only 1 to 50. so if nums[i] == 50 and k==1 so u have to subtract 49 and if nums[i]==1 and k==50 so you have to add 49 that's why from -50 to 50 # Approach <!-- Describe your approach to solving the problem. --> count the initial freq of k in nums your ans can't be less than that iterate x from -50 to 50 and use sliding window shrink the subarray only when the freq of k becomes less than the original freq we counted before. # Complexity - Time complexity: O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int n=nums.size(); unordered_map<int,int>mp; for(auto it:nums) mp[it]++; int t=mp[k]; int ans=0; for(int x=-50;x<=50;x++){ int i=0; int j=0; int f=0; int subkcnt=0; int cnt=0; while(j<n){ if(nums[j]==k) subkcnt++; else if(nums[j]+x==k) cnt++; while(i<=j && t-subkcnt+cnt<t){ if(nums[i]==k) subkcnt--; else if(nums[i]+x==k) cnt--; i++; } ans=max(ans,t-subkcnt+cnt); j++; } } return ans; } }; ```
1
0
['C++']
1
maximum-frequency-after-subarray-operation
Java Real O(n) 100% PrefixCount Solution | No Nested Loop
java-simple-linear-time-100-prefixcount-bu9zl
IntuitionAt each index j, we need to find index i such that valuecan be maximised Then iterate across all indices j of nums to find the resultApproachComplexity
akandak
NORMAL
2025-01-26T05:37:18.224260+00:00
2025-01-27T08:02:29.946192+00:00
124
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> At each index `j`, we need to find index `i` such that value ``` { 1. num of ks in [0..i-1] + 2. max freq of any char that we want to convert to k in subarray [i..j] + 3. num of ks in [j+1...last] } ``` can be maximised Then iterate across all indices `j` of `nums` to find the result # Approach <!-- Describe your approach to solving the problem. --> ``` { 1. (num of ks in [0..i-1]) --> keep track of this using prefix count of ks i.e *prefixCountK* 2. (max freq of any char that we want to convert to k in subarray [i..j]) --> store (prefixCountK - prefixCountNumI) for each number *n = nums[i]* in [0..51] i.e. maxval[i] = max(prefixCountK - freq[n]) --> when the same number n comes again at j, maxval[j] + freq[n] gives the value of *1 + 2* 3. (num of ks in [j+1...last]) --> *totalK - prefixCountK* } ``` # Complexity - Time complexity: O(n) Even if nums[i] > 51, this algo would be in linear time - Space complexity: O(51) # Code ```java [] class Solution { public int maxFrequency(int[] nums, int k) { int totalK = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] == k) totalK++; } int prefixCountK = 0; int[] freq = new int[51]; int[] maxval = new int[51]; int res = 0; for (int j = 0; j < nums.length; j++) { int n = nums[j]; maxval[n] = Math.max(maxval[n], prefixCountK - freq[n]); prefixCountK += (n == k) ? 1 : 0; freq[n]++; res = Math.max(res, (totalK - prefixCountK) + maxval[n] + freq[n]); } return res; } } ```
1
0
['Prefix Sum', 'Java']
0
maximum-frequency-after-subarray-operation
Simple Solution || Kadane's || easy to understand.
simple-solution-kadanes-easy-to-understa-11zd
Approachsolved this after hints just as they say fix any nums[i]. compute the contribution of nums[i] to ans frequency in O(n). just read inline commments you
naveen_gunnam
NORMAL
2025-01-26T05:10:47.695717+00:00
2025-01-26T05:10:47.695717+00:00
59
false
# Approach <!-- Describe your approach to solving the problem. --> solved this after hints just as they say fix any nums[i]. compute the contribution of nums[i] to ans frequency in O(n). just read inline commments you will get it. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(m*n) , m - 10^5 len of nums n - 50 nums[i] range - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1) , no extra space used # Code ```java [] class Solution { public int maxFrequency(int[] nums, int k) { int ks = 0; for(int i : nums ){ if(i==k) ks++; } int ans = ks; for(int i = 1 ; i<51 ; i++ ){ if(k==i) continue; int max = 0; int curr = 0; for(int n : nums){ if(n==k) curr--; // because it will get changed when we apply operation and it has been already counted in ks. if(n==i) curr++; if(curr<0) curr = 0; // we don't want to carry negative baggage , if instead we can ignore max = Math.max(curr,max); } ans = Math.max(ans,max+ks); } return ans; } } ```
1
0
['Java']
1
maximum-frequency-after-subarray-operation
Python Solution | Prefix sums O(n), Beats 100% in Contest
python-solution-prefix-sums-on-beats-100-ren0
ApproachWe want to find the interval at which to apply the operation. If the interval is over a subarray where k does not occur, then the mode of that subarray
vincentcai70
NORMAL
2025-01-26T05:09:04.779189+00:00
2025-01-26T05:09:40.027906+00:00
148
false
# Approach We want to find the interval at which to apply the operation. If the interval is over a subarray where k does not occur, then the mode of that subarray is added to the final result. However, if there are occurences of k in that interval, and the mode is not k in that interval, than those occurences of k will no longer be k after the operation. Our goal is to find an interval where the net addition to the number of occurences of k is maximized. We do this by keeping track of the first occurence of every element in nums, and everytime we find another occurence, we see how many values of k are between the first and current occurence. Occurences of the other number, minus occurences of k, is equal to our net addition of k occurences after the operation. However, if net is ever zero or negative, meaning there are more or equal occurences of k than some other element, it is no longer worth it to do the operation over that interval, so we set the "first occurence" to the current index. Keep a prefix sum of the number of occurences of k by a specific index in the array. This way, we can look up how many occurences of k are between indices i and j in constant time. # Complexity - Time complexity: O(n) - Space complexity: O(n) # Code ```python3 [] class Solution: def maxFrequency(self, nums: List[int], k: int) -> int: freq,first,last = [0]*51,[-1]*51,[-1]*51 res = 0 # prefix sum occurences of k ps = [0] for a in nums: ps.append(ps[-1] + (1 if a ==k else 0)) #i + 1 is number of ks at or before index i # for each value you can target, find first, last occurence, and ks inbetween for i in range(len(nums)): v = nums[i] if v == k: continue freq[v] += 1 if first[v] == -1: first[v] = i last[v] = i #now calculate if removing ks is worth it numberOfKs = ps[last[v]+1] - ps[first[v]+1]#number of ks between first and last occurence net = freq[v] - numberOfKs if net <= 0: first[v] = i freq[v] = 1 res = max(res,net) return res + ps[-1] ```
1
0
['Hash Table', 'Prefix Sum', 'Python3']
1
maximum-frequency-after-subarray-operation
Easy Beginner friendly || Java || Python || C++
easy-beginner-friendly-java-python-c-by-7g5ax
Complexity Time complexity: O(50*n) - for loop Overall O(n) Space complexity: O(1) Code
Akshay_Kadamm
NORMAL
2025-01-26T05:02:46.680516+00:00
2025-01-26T05:02:46.680516+00:00
145
false
# Complexity - Time complexity: O(50*n) - for loop #### Overall O(n) - Space complexity: O(1) # Code ```java [] class Solution { public int maxFrequency(int[] nums, int k) { int Ktotal = 0; for (int num : nums) { if (num == k) { Ktotal++; } } int max = 0; for (int n = 1; n <= 50; n++) { if (n == k) continue; int x = k - n; int curr = 0; int maxCurr = 0; for (int num : nums) { if (num == n) { curr++; } else if (num == k) { curr--; } if (curr < 0) { curr = 0; } if (curr > maxCurr) { maxCurr = curr; } } if (maxCurr > max) { max = maxCurr; } } return Ktotal+max; } } ``` ``` Python [] class Solution: def maxFrequency(self, nums: List[int], k: int) -> int: Ktotal = nums.count(k) maxFreq = 0 for n in range(1, 51): if n == k: continue x = k - n curr = 0 maxCurr = 0 for num in nums: if num == n: curr += 1 elif num == k: curr -= 1 if curr < 0: curr = 0 maxCurr = max(maxCurr, curr) maxFreq = max(maxFreq, maxCurr) return Ktotal + maxFreq ``` ``` C++ [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int Ktotal = count(nums.begin(), nums.end(), k); int maxFreq = 0; for (int n = 1; n <= 50; n++) { if (n == k) continue; int x = k - n; int curr = 0; int maxCurr = 0; for (int num : nums) { if (num == n) { curr++; } else if (num == k) { curr--; } if (curr < 0) { curr = 0; } maxCurr = max(maxCurr, curr); } maxFreq = max(maxFreq, maxCurr); } return Ktotal + maxFreq; } }; ```
1
0
['Python', 'C++', 'Java']
0
maximum-frequency-after-subarray-operation
Try all numbers
try-all-numbers-by-optimizor-c0cu
Code
Optimizor
NORMAL
2025-01-26T04:42:53.888271+00:00
2025-01-26T04:42:53.888271+00:00
95
false
# Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int tk = 0; for (auto it : nums) { if (it == k) { tk++; } } int maxi = 0; for (int i = 1; i <= 50; i++) { if (i == k && 1) continue; int cs = 0; int lm = 0; for (auto it : nums) { if (it == i && 1) cs += 1; else if (it == k && 1) cs -= 1; if (cs < 0 && 1) cs = 0; if (cs > lm && 1) lm = cs; } if (lm > maxi && 1) maxi = lm; } return tk + maxi; } }; ```
1
0
['C++']
0
maximum-frequency-after-subarray-operation
loop on x and some state transitions between 3 states
loop-on-x-and-some-state-transitions-bet-kpbd
Code
nishsolvesalgo
NORMAL
2025-01-26T04:31:50.535945+00:00
2025-01-26T04:31:50.535945+00:00
16
false
# Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int maxFreq = 0; for(int x=-51; x<52; x++){ int KwithoutModifying = 0, KwithModifying = 0, Kmodified = 0; for(int i=0; i<nums.size(); i++){ int modified = nums[i] + x; if(nums[i] == k) Kmodified = max(Kmodified + 1, KwithModifying + 1); if(modified == k) KwithModifying = max(KwithModifying + 1, KwithoutModifying + 1); if(nums[i] == k) KwithoutModifying++; maxFreq = max({maxFreq, KwithoutModifying, KwithModifying, Kmodified}); } } return maxFreq; } }; ```
1
0
['C++']
0
maximum-frequency-after-subarray-operation
Best Solution ||Beats 100%||Why kadane Algorithm|| O(n)||C++||java||python
best-solution-beats-100why-kadane-algori-rbk3
IntuitionWhenever maximum sum probelm give atleast one view to kadane algorithm as it does a thing ino(n) complexityApproachMy approach is simple.we have to max
Da_btc
NORMAL
2025-01-26T04:16:01.799034+00:00
2025-01-26T04:16:01.799034+00:00
48
false
# Intuition Whenever maximum sum probelm give atleast one view to kadane algorithm as it does a thing ino(n) complexity # Approach My approach is simple. we have to maximize the subarray size from which a number to be subtrcted then we will define k-nums[i] as the number to be decreased by thus make a set to store **Ditinct** numbers so that we may then traverse for that difference freqency in the original array. now we cant traverse the nums array outside as nums.size()<=1e5> thus use nums[i]<=50 thus we may have maximum 50 elements in the unordered set thus we can tarverse thrugh each and count from array for each value in set We will store the number of elements in the array equal to k first. now trans array init by 0, will store 1 if nums[i]-x==k and -1 if nums[i]==k as we have stored it already thus we have to reduce by 1 here to make it count once only. then kadane function will tell the maximum subarraysum of 1s so that we will get the max freq one. # Complexity - Time complexity: O(50*(n+n))+O(n)=O(100*n)=O(n) - Space complexity: Set will take max of 50 size and trans vectors will take n thus O(n)+O(50)=O(n) # Code ```cpp [] class Solution { public: int ka(const vector<int>& arr) { int maxSoFar = arr[0], currentMax = arr[0]; for (int i = 1; i < arr.size(); i++) { currentMax = max(arr[i], currentMax + arr[i]); maxSoFar = max(maxSoFar, currentMax); } return maxSoFar; } int maxFrequency(vector<int>& nums, int k) { int tK = 0; for (int n : nums) { if (n == k) tK++; } unordered_set<int> xVals; for (int n : nums) { xVals.insert(k - n); } int mC = tK; vector<int> nArr = nums; for (int x : xVals) { int cC; if (x == 0) { cC = tK; } else { vector<int> trans(nums.size(), 0); for (int i = 0; i < nums.size(); i++) { if (nums[i] == k - x) trans[i] = 1; else if (nums[i] == k) trans[i] = -1; } cC = ka(trans) + tK; } mC = max(mC, cC); } return mC; } }; ``` ```Java [] import java.util.*; class Solution { // Helper function to calculate the maximum subarray sum (Kadane's Algorithm) public int calculateMaxSubarraySum(int[] arr) { int maxSoFar = arr[0], currentMax = arr[0]; for (int i = 1; i < arr.length; i++) { currentMax = Math.max(arr[i], currentMax + arr[i]); maxSoFar = Math.max(maxSoFar, currentMax); } return maxSoFar; } public int maxFrequency(int[] nums, int k) { // Step 1: Count the occurrences of the number 'k' in the array int countK = 0; for (int num : nums) { if (num == k) countK++; } // Step 2: Create a set of potential transformation values (k - num) Set<Integer> transformationValues = new HashSet<>(); for (int num : nums) { transformationValues.add(k - num); } // Step 3: Initialize the maximum frequency as the count of 'k' int maxCount = countK; // Step 4: Create a copy of nums for transformation evaluations int[] numsCopy = Arrays.copyOf(nums, nums.length); // Step 5: Iterate through each potential transformation value and evaluate the result for (int transformation : transformationValues) { int currentCount; // If transformation value is 0, simply use the count of 'k' if (transformation == 0) { currentCount = countK; } else { int[] transformationArray = new int[nums.length]; // Step 6: Apply transformations to the array for (int i = 0; i < nums.length; i++) { if (nums[i] == k - transformation) transformationArray[i] = 1; else if (nums[i] == k) transformationArray[i] = -1; } // Step 7: Calculate the maximum subarray sum with the transformed array currentCount = calculateMaxSubarraySum(transformationArray) + countK; } // Step 8: Update the maximum frequency found maxCount = Math.max(maxCount, currentCount); } // Step 9: Return the maximum frequency return maxCount; } } ``` ```Python[] class Solution: def calculate_max_subarray_sum(self, arr): max_so_far = current_max = arr[0] for i in range(1, len(arr)): current_max = max(arr[i], current_max + arr[i]) max_so_far = max(max_so_far, current_max) return max_so_far def maxFrequency(self, nums, k): count_k = nums.count(k) transformation_values = set(k - num for num in nums) max_count = count_k nums_copy = nums[:] for transformation in transformation_values: if transformation == 0: current_count = count_k else: transformation_array = [0] * len(nums) for i in range(len(nums)): if nums[i] == k - transformation: transformation_array[i] = 1 elif nums[i] == k: transformation_array[i] = -1 current_count = self.calculate_max_subarray_sum(transformation_array) + count_k max_count = max(max_count, current_count) return max_count ```
1
0
['Python', 'C++', 'Java']
0
maximum-frequency-after-subarray-operation
Trying out all differences and Getting the most Optimal Out of IT
trying-out-all-differences-and-getting-t-zmk8
IntuitionAs we know there is a specific and if in constraints we are given num[i] ranges from 1 to 50 we can check for all differences we get from k-nums[i]
thewizard641
NORMAL
2025-01-26T04:10:52.621801+00:00
2025-01-26T04:10:52.621801+00:00
189
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> As we know there is a specific and if in constraints we are given num[i] ranges from 1 to 50 we can check for all differences we get from k-nums[i] as one of the diff is the main hero of this short story which will help to get out the maximum potential of our candidate k # Approach <!-- Describe your approach to solving the problem. --> My approach can be made space optimised a bit but at that moment I created a diff vector and then for each diff i was simply checking the maximum frequency i can get for that too check Kadane Algorithm is best which can provide u the subarray the most optimal one. ;) while targetting specific difference we know other differences ar euseless so dont add it while updating ur sum and instead increment sum while getting ur desired difference and decrement ur sum while difference is 0 (that means required k) ...we are decrementing as for now we getting the subarray the most optimal without contribution of k The curtain drops and story ends !! # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(50*N) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(N) # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { vector<int> req; unordered_map<int, int> mp; int total = 0; int mind=INT_MAX; int maxd=INT_MIN; for (int i = 0; i < nums.size(); i++) { if (nums[i] == k) total++; req.push_back(k - nums[i]); if(k-nums[i]!=0) mind=min(mind,k-nums[i]); if(k-nums[i]!=0) maxd=max(maxd,k-nums[i]); mp[k - nums[i]]++; } int mg = 0; cout<<maxd<<" "<<mind<<endl; for (int i = mind; i <= maxd; i++) { if (i == 0 || mp.find(i) == mp.end()) continue; int request = i; int currsum = 0; int lm = 0; for (int j = 0; j < req.size(); j++) { if (req[j] == request) currsum++; else if (req[j] == 0) currsum--; if (currsum < 0) currsum = 0; lm = max(currsum, lm); } mg = max(mg, lm); } return total + mg; } }; ```
1
1
['Array', 'Hash Table', 'Prefix Sum', 'C++']
1
maximum-frequency-after-subarray-operation
Kadane's Algorithm / Change each number into K
change-each-number-into-k-by-cinderace-tafv
IntuitionThe idea is similar conceptually to Kadane's algorithm - we test each number, and attempt to create a subarray with a maximum "score" by converting eac
cinderace
NORMAL
2025-01-26T04:08:20.174974+00:00
2025-01-26T04:16:36.112889+00:00
182
false
# Intuition The idea is similar conceptually to Kadane's algorithm - we test each number, and attempt to create a subarray with a maximum "score" by converting each occurence of this number to K. Each time we find the number we're testing, we add 1 point. If we find "K", we subtract one point. If this score is negative, there's no point in continuing, so we restart at 0 from the next index (Kadane). # Complexity - Time complexity: O(n) - Space complexity: O(1) (counter is max size 50) # Code ```python3 [] class Solution: def maxFrequency(self, nums: List[int], k: int) -> int: c = Counter(nums) # Default maximum answer will always be how many "k" integers already exist ans = c[k] # Only need 1-50 as per the restraints for i in range(51): # We've already considered i == k in our default answer, and don't care if i not in nums if i not in c or i == k: continue start_sub, score, ks = 0, 0, 0 while start_sub < len(nums): # Current subarray +1 if nums[start_sub] == i: score += 1 # Current subarray -1 elif nums[start_sub] == k: ks += 1 # Restart if score is negative if ks > score: score, ks = 0, 0 # Subtract number of "k" integers in our subarray from total number that occur ans = max(ans, score + (c[k] - ks)) start_sub += 1 return ans ```
1
0
['Python3']
0
maximum-frequency-after-subarray-operation
Simplest solution || Beginner friendly || Best time complexity
simplest-solution-beginner-friendly-best-j6gw
Approach Count the initial occurrences of k. Iterate over all possible values v (1 to 50) except k. Find the best subarray where we can transform v to k using o
RayugaMaxx
NORMAL
2025-01-26T04:05:14.948164+00:00
2025-01-26T04:05:14.948164+00:00
122
false
# Approach <!-- Describe your approach to solving the problem. --> 1. Count the initial occurrences of k. 2. Iterate over all possible values v (1 to 50) except k. 3. Find the best subarray where we can transform v to k using one operation. 4. Keep track of the maximum gain in the number of ks. 5. Return the sum of the initial count and the best gain. # Complexity - Time complexity: O(N) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int countK = count(nums.begin(), nums.end(), k); int maxIncrease = 0; for (int i = 1; i <= 50; i++) { if (i == k) continue; int delta = k - i; int balance = 0, peak = 0; for (int j = 0; j < nums.size(); j++) { balance += (nums[j] == i) ? 1 : (nums[j] == k) ? -1 : 0; if (balance < 0) balance = 0; peak = max(peak, balance); } maxIncrease = max(maxIncrease, peak); } return countK + maxIncrease; } }; ```
1
0
['C++']
1
maximum-frequency-after-subarray-operation
Suffix sum + frequency array
suffix-sum-frequency-array-by-jkulanko-m4ws
IntuitionCreate a suffix sum counting number of k's in the array. Then iterate through the array and at each index increment frequency by one and decrement by
jkulanko
NORMAL
2025-01-26T04:02:29.984424+00:00
2025-01-26T04:05:30.051197+00:00
309
false
# Intuition Create a suffix sum counting number of k's in the array. Then iterate through the array and at each index increment frequency by one and decrement by the number of k's since the last time you saw the number. # Complexity - Time complexity: $$O(50n)$$ # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { vector<int> v(51); vector<int> suf(nums.size()); if (nums[nums.size() - 1] == k) suf[nums.size() - 1]++; for (int i = nums.size() - 2; i >= 0; i--) { suf[i] = suf[i + 1]; if (nums[i] == k) suf[i]++; } int j = 0; int ans = suf[0]; vector<int> last(51, -1); while (j < nums.size()) { if (nums[j]!=k) { if (last[nums[j]] != -1) v[nums[j]] -= (suf[last[nums[j]]] - suf[j]); if (v[nums[j]] < 0) v[nums[j]] = 0; last[nums[j]] = j; v[nums[j]]++; } for (int i = 0; i < 51; i++) { ans = max(ans, (j > 0 ? suf[0] - suf[j] : 0) + (j < nums.size() - 1 ? suf[j + 1] : 0) + v[i]); } j++; } return ans; } }; ```
1
0
['C++']
0
maximum-frequency-after-subarray-operation
Mathematical Proof + Video Explanation | Prefix Sum trick | C++
mathematical-proof-video-explanation-pre-83eg
IntuitionPrefix Sums and brute forceApproachCode
saber2k18
NORMAL
2025-01-26T04:02:28.611441+00:00
2025-01-26T04:02:28.611441+00:00
386
false
# Intuition Prefix Sums and brute force # Approach https://www.youtube.com/watch?v=hRI2XerqxT4 # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int n = nums.size(); int ans = 0; for(int e=1;e<=50;++e){ vector<int> v; for(int j=0;j<n;++j){ if((nums[j]==e) || (nums[j]==k)){ v.push_back(nums[j]); } } int sz = v.size(); vector<int> p(sz, 0), s(sz, 0); for(int i=0;i<sz;++i){ p[i]=(i>0?p[i-1]:0)+((v[i]==k)?1:0); } for(int i=sz-1;i>=0;--i){ s[i]=(i+1<sz?s[i+1]:0)+((v[i]==k)?1:0); } int mn = 1e9; for(int j=0;j<sz;++j){ ans = max(ans, j+1-p[j]+(j+1<sz?s[j+1]:0)); mn = min(mn, j-2*p[j]); ans = max(ans, j-p[j]-mn+(j+1<sz?s[j+1]:0)); } } return ans; } }; ```
1
0
['C++']
1
maximum-frequency-after-subarray-operation
Easy Approach using C++
easy-approach-using-c-by-vaibhav_8101-v72n
IntuitionSo as we have to find the max number of element equal to target ,we can get after performing the operation on the subarray, one way is to make all the
vaibhav_8101
NORMAL
2025-03-07T18:36:50.297985+00:00
2025-03-07T18:36:50.297985+00:00
5
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> So as we have to find the max number of element equal to target ,we can get after performing the operation on the subarray, one way is to make all the subarray and check how many element you can make equal to k, but we will get TLE because of 1e5 len contraint. Another thing to observe is the value of nums[i]<=50 and nums[i]>=1 , so we can think of processing the each element separately and mazimise our answer. # Approach <!-- Describe your approach to solving the problem. --> Let's suppose your target is 10 and following is the subarray 3 3 10 10 10 10 3 3 10 10 10 If you take the entire subarray then you need to process the target element also and you will not get the max answer. So we can change the given array in the following way 1 1 -1 -1 -1 -1 1 1 -1 -1 -1 We have considered one for the candidate element, and -1 for target element,now our task is to find the max sum subarray , which we can easily find using the Kadane algorithm. After find the max sum , we can add the total count of target element to the max_sum , to get the maximumn possible frequency using that element. for above case max_sum=2 and count of 10 is 7 so our final freq of target element is 2+7=9 # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n^2) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(n^2) # Code ```cpp [] class Solution { public: int kadane(vector<int>&temp) { int sum=0; int ans=0; for(int i=0;i<temp.size();i++) { sum+=temp[i]; if(ans<sum) { ans=sum; } else if(sum<0)sum=0; } return ans; } int maxFrequency(vector<int>& nums, int k) { //hk vector<vector<int>> allSubarrays; int ans=0; for(int i=1;i<=50;i++) { // if(i>k) break; vector<int> temp; int countTar=0; for(int j=0;j<nums.size();j++) { if(nums[j]==k){ temp.push_back(-1); countTar++; } else if(nums[j]==i)temp.push_back(1); else temp.push_back(0); } int max_sum=kadane(temp)+countTar; ans=max(ans,max_sum); } return ans; } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
C++ | Kadane
c-kadane-by-kena7-lxsn
Code
kenA7
NORMAL
2025-02-25T05:55:28.842302+00:00
2025-02-25T05:55:28.842302+00:00
4
false
# Code ```cpp [] class Solution { public: int find(int change,int k, vector<int>& nums) { int kc=0; for(auto &x:nums) kc+=(x==k); if(change==k) return kc; int res=kc,curr=0; for(auto &x:nums) { if(x==change) curr++; else if(x==k) curr--; if(curr<0) curr=0; res=max(res,curr+kc); } return res; } int maxFrequency(vector<int>& nums, int k) { int res=0; for(int i=1;i<=50;i++) { res=max(res,find(i,k,nums)); } return res; } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
Only calculate the delta and transform it to longest sum subarray.
only-calculate-the-delta-and-transform-i-hvkz
IntuitionApproachComplexity Time complexity: Space complexity: Code
labao
NORMAL
2025-02-24T16:12:13.093328+00:00
2025-02-24T16:12:13.093328+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int maxFrequency(int[] nums, int k) { int[] subarray = new int[nums.length]; int res = 0; int numOfK = 0; for (int i = 1; i <= 50; ++i) { if (i == k) { continue; } int max = Integer.MIN_VALUE; for (int j = 0; j < nums.length; ++j) { int delta = nums[j] == i ? 1 : (nums[j] == k ? -1 : 0); if (j == 0) { subarray[j] = delta; } else { subarray[j] = Math.max(subarray[j - 1] + delta, delta); } max = Math.max(max, subarray[j]); } res = Math.max(res, max); } for (int num : nums) { if (num == k) { res ++; } } return res; } } ```
0
0
['Java']
0
maximum-frequency-after-subarray-operation
[C++] Kadane for Each Value in Range, 100% Space (0ms), ~98% Space (96.33MB)
c-kadane-for-each-value-in-range-100-spa-vwws
This problem can be solved by figuring out that: on one hand, we have the natural occurrences of values in nums already matching k; on the other hand, having mu
Ajna2
NORMAL
2025-02-15T11:01:04.286550+00:00
2025-02-15T11:01:04.286550+00:00
16
false
This problem can be solved by figuring out that: * on one hand, we have the natural occurrences of values in `nums` already matching `k`; * on the other hand, having multiple repeated values in a given interval can mean more matches, even if we alter some of the natural occurrences, since we can take all the values in that range, lower them all by the same amount and get more instances of `k`. Now, while this task might lead us to think about some daunting DP approach with non trivial logic for each possible interval, as a matter of fact we can actually approach this problem in a much easier way if we keep track of the frequencies of all the values we found so far in a guise similar to Kadane algorithm to find the longest convenient sequence of identical values in a given interval. Our best result would be the sum of all the natural occurrences of `k`, plus what we can get in the interval where we are allowed to change all the values. Keeping track of the frequncy of each value in the input (guaranteed to be in the `[1, 50]` range), we can parse `nums` having two different scenarios for each value `n`: * if `n != k`, we will just update the frequency of `n` and see if this frequency is our new maximum; * if `n == k`, then we will increase our counter variable that keeps track of how many `k`s we found so far naturally AND decrease the frequencies of all the other values (since finding a new `k` here basically means losing it when we do our allowed operation), bearing in mind that we can never have any negative frequence, so each value will have to be the maximum between its now reduced value and `0`. For example, having this situation: ```cpp cdakkabakbkacacakcd ``` Using our logic we will find that we have `5` `k`s in total and that the interval where is is more convenient to do our operation is here: ```cpp cdakkabakbkacacakcd | | ``` In that interval we would lose `2` `k`s, but gain much more by converting all the `5` `a`s inside; going with our algorithm we would find that the net gain inside that interval is `3` (having kept the frequency for the value `a` reduced by the number of `k` encountered so far). Our algorithm also shows how starting earlier would not have worked for example extending the range like this: ```cpp cdakkabakbkacacakcd | | ``` It can be seen that including the first `a` value would not have made it worth it, since it would cost us `2` `k`s - after the first `k`, the maximum frequency of `a` would already have been `0` according to our rules (and stays `0` after the second `k`), which means that would not be a good tradeoff for us. To do so, we will start with a few support variables: * `cnt` will count how many occurrences of `k` we will find, initially set to `0`; * `maxFreq` will store the longest frequence we can find in the string (again, subtracing each time we meet a value matching `k`); * `freqs` will store the ongoing value of our frequencies. Next we are going to parse each value `n` in `nums` and: * if `n` equals `k`, we will: * increase `cnt` by `1`; * update each frequence in range to the maximum between its current value reduced by `1` and `0`; * otherwise, we will just: * increase `freqs[n]` by `1`; * update `maxFreq` to be the maximum between its current value and the increased value of `freqs[n]`. Once done, we can just `return` `cnt` plus `maxFreq` :) # Complexity - Time complexity: $$O(n * m)$$ (with `m` being the extension of the range of values - 50 in the current specs) - Space complexity: $$O(m)$$ # Code ```cpp constexpr int MAX_RANGE_VAL = 50, MAX_RANGE_LMT = MAX_RANGE_VAL + 1; class Solution { public: int maxFrequency(vector<int> &nums, int k) { // support variables int cnt = 0, maxFreq = 0, freqs[MAX_RANGE_LMT] = {}; // parsing nums for (int n: nums) { // 1st case: match with k if (n == k) { cnt++; for (int i = 1; i < MAX_RANGE_LMT; i++) { maxFreq = max(maxFreq, freqs[i] = max(0, freqs[i] - 1)); } } else maxFreq = max(maxFreq, ++freqs[n]); } return cnt + maxFreq; } }; ``` We might also try to flip the logic around and run through `nums` to verify the conditions for each value in the range; extra points if we just populate an array of `boolean` values to mark which values are actually `available` in `nums` and potentially avoid needless runs. It runs much slower than I expected, but it also uses some less memory. # Complexity - Time complexity: $$O(n * m)$$ (with `m` being the extension of the range of values - 50 in the current specs) - Space complexity: $$O(m)$$ # Code ```cpp constexpr int MAX_RANGE_VAL = 50, MAX_RANGE_LMT = MAX_RANGE_VAL + 1; class Solution { public: int maxFrequency(vector<int> &nums, int k) { // support variables int cnt = 0, maxFreq = 0; bool available[MAX_RANGE_LMT] = {}; // finding the available values for (int n: nums) { available[n] = true; if (n == k) cnt++; } // parsing nums for (int i = 1, currFreq; i < MAX_RANGE_LMT; i++) { // ignoring values not in nums if (!available[i]) continue; // parsing nums to look for matches to i currFreq = 0; for (int n: nums) { // 1st case: match with k if (n == k) { maxFreq = max(maxFreq, currFreq = max(0, currFreq - 1)); } else if (n == i) maxFreq = max(maxFreq, ++currFreq); } // checking leftover frequencies maxFreq = max(maxFreq, currFreq = max(0, currFreq - 1)); } return cnt + maxFreq; } }; ``` # Brag ![image.png](https://assets.leetcode.com/users/images/9756e585-3982-4f91-8a00-3b2b7efdb65e_1739617256.4426334.png)
0
0
['Array', 'Dynamic Programming', 'Greedy', 'C++']
0
maximum-frequency-after-subarray-operation
scala twoliner
scala-twoliner-by-vititov-lud6
null
vititov
NORMAL
2025-02-13T18:15:38.553133+00:00
2025-02-13T18:15:38.553133+00:00
4
false
```scala [] object Solution { def maxFrequency(nums: Array[Int], k: Int): Int = { val nMap = nums.groupMapReduce(identity)(_ => 1)(_ + _) nMap.keysIterator.filterNot(_ == k).map{num0 => nums.iterator.scanLeft((0,0)){case (inp@(kCnt1,nCnt),num) => if(num==num0) (kCnt1,nCnt+1) else if(num==k && kCnt1>=nCnt) (0,0) else if(num==k) (kCnt1+1,nCnt) else inp }.map{case (kCnt1,nCnt) => -kCnt1+nCnt}.max max 0 }.maxOption.getOrElse(0) + nMap.getOrElse(k,0) } } ```
0
0
['Hash Table', 'Greedy', 'Prefix Sum', 'Scala']
0
maximum-frequency-after-subarray-operation
Easy Python Solution
easy-python-solution-by-sb012-bn2v
Code
sb012
NORMAL
2025-02-07T23:28:22.271000+00:00
2025-02-07T23:28:22.271000+00:00
8
false
# Code ```python3 [] class Solution: def maxFrequency(self, nums: List[int], k: int) -> int: answer = 0 for i in range(1, 50 + 1): if i == k: continue maxi = 0 curr = 0 for j in nums: if j == i: curr += 1 elif j == k: curr -= 1 maxi = max(maxi, curr) if curr < 0: curr = 0 answer = max(answer, maxi) return answer + nums.count(k) ```
0
0
['Python3']
0
maximum-frequency-after-subarray-operation
Javascript | Kandane | O(n)
javascript-kandane-on-by-aryonbe-wdw3
Code
aryonbe
NORMAL
2025-02-07T07:51:06.116077+00:00
2025-02-07T07:51:06.116077+00:00
7
false
# Code ```javascript [] /** * @param {number[]} nums * @param {number} k * @return {number} */ var maxFrequency = function(nums, k) { const count = new Map(); for(let num of nums){ count.set(num, (count.get(num) || 0) + 1); } let kandane = (b)=>{ let cur = 0; for(let num of nums){ if(num === k){ cur--; } if(num === b){ cur++; } if(cur < 0) cur = 0; res = Math.max(res, cur); } return res; } let res = 0; for(let b = 1; b <= 50; ++b){ res = Math.max(res, kandane(b)); } return res + (count.get(k) || 0); }; ```
0
0
['JavaScript']
0
maximum-frequency-after-subarray-operation
Java Simple Solution with Kadane's Algo || simple || easy code
java-simple-solution-with-kadanes-algo-s-liyi
IntuitionSo here we need to understand how Kadane's algorithm is working here so in this problem we need to actually find out the maximum frequency after survey
palindrome_kasak
NORMAL
2025-02-06T11:31:28.248068+00:00
2025-02-06T11:31:28.248068+00:00
7
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> So here we need to understand how Kadane's algorithm is working here so in this problem we need to actually find out the maximum frequency after survey operations so when we see Subarray and we want to take out a subarray and make a operations and then make the count of K maximum can we say this as take out a subarray where we have a max frequency number and less or zero k => so that we can convert that number into k # Complexity - Time complexity:O(n2) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int helper(int [] nums , int target , int k){ int curr=0; int max=0; for(int num: nums){ if(num==target){ curr++; } if(num==k) curr--; if(curr<0) curr=0; max=Math.max(max,curr); } return max; } public int maxFrequency(int[] nums, int k) { int n= nums.length; int maxFreq=0; int ans=0; Map<Integer , Integer> frequencyMap = new HashMap<>(); for(int num: nums){ frequencyMap.put(num,frequencyMap.getOrDefault(num,0)+1); } for (int value : frequencyMap.keySet()) { maxFreq = Math.max(maxFreq, helper(nums,value,k)); } return maxFreq +frequencyMap.getOrDefault(k, 0) ; } } ```
0
0
['Array', 'Hash Table', 'Java']
0
maximum-frequency-after-subarray-operation
Using the kadanes algorithm
using-the-kadanes-algorithm-by-dyaganikh-ywdp
Intuitionselect the subarray which in which the maximum frequent element is present add the frequency of the element k and the count of maximum frequent element
dyaganikhil
NORMAL
2025-02-06T09:26:19.747725+00:00
2025-02-06T09:26:19.747725+00:00
8
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. -->count the number of elements which are k select the subarray which in which the maximum frequent element is present add the frequency of the element k and the count of maximum frequent element. # Approach <!-- Describe your approach to solving the problem. --> Find the frequency of the element k. use the kadanes algorithm for the elements *(1<=m<=50)* For every element check if the element is equal to element in the array and add increase the count and decrease if the element is equal to the element k get the maximum count return count+frequency of the element k # Complexity - Time complexity: O(n*50) = O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int originFreqCount= count(nums.begin(),nums.end(),k),maxi=0; for(int m=1;m<=50;++m){ if(m==k) continue; int curMaxi=0,cur=0; for(auto i:nums){ cur+=i==m?1:i==k?-1:0; cur=max(cur,0); curMaxi=max(curMaxi,cur); } maxi=max(maxi,curMaxi); } return maxi+originFreqCount; } }; ```
0
0
['Array', 'Prefix Sum', 'C++']
0
maximum-frequency-after-subarray-operation
Kadane's Algorithm approach [C++/Java/Python] || Beats 100%
kadanes-algorithm-approach-cjavapython-b-y0pj
This question is based on use of kadane's algorithmKadane's Algorithm Kadane’s algorithm typically solves the maximum subarray sum problem by maintaining: A cur
be_fighter
NORMAL
2025-02-04T20:05:49.138011+00:00
2025-02-04T20:05:49.138011+00:00
21
false
This question is based on use of kadane's algorithm # Kadane's Algorithm 1. Kadane’s algorithm typically solves the maximum subarray sum problem by maintaining: 2. A current sum that represents the best sum ending at the current element. 3. A global maximum that stores the best sum found so far. 4. The key insight is that if the current sum becomes negative, it should be reset to zero, as negative sums cannot contribute positively to future subarrays. # Approach 1. We treat each element comparison as a pseudo "value." 2. Increment or decrement the sum based on whether the current element matches the target frequency i or the element k. # Outer Loop (1 to 50) 1. This loop iterates over all possible target elements (from 1 to 50). 2. We treat each possible element i as the candidate for maximum frequency. # Inner Loop (Kadane's Application) 1. If nums[j] == i, increment the sum since it aligns with our current target frequency. 2. If nums[j] == k, decrement the sum because k reduces our ability to maintain a valid subarray with the target i. Sum Reset: 3. If sum < 0, reset it to 0 (similar to Kadane’s reset for negative sums). # Final Adjustment Global Maximum Update: 1. After the loop, the result is adjusted by adding mp[k], accounting for the frequency of k itself to ensure it's not excluded when forming the maximum frequency. # Complexity - Time complexity: O(N*50) - Space complexity: O(1) # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { unordered_map<int, int> mp; for (auto it : nums) mp[it]++; int ans = 0; for (int i = 1; i <= 50; i++) { int sum = 0; for (int j = 0; j < nums.size(); j++) { if (nums[j] == i) sum++; if (nums[j] == k) sum--; if (sum < 0) sum = 0; ans = max(ans, sum); } } return ans + mp[k]; } }; ``` ```java [] import java.util.HashMap; import java.util.Map; class Solution { public int maxFrequency(int[] nums, int k) { Map<Integer, Integer> frequencyMap = new HashMap<>(); for (int num : nums) { frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); } int ans = 0; for (int i = 1; i <= 50; i++) { int sum = 0; for (int num : nums) { if (num == i) sum++; if (num == k) sum--; if (sum < 0) sum = 0; ans = Math.max(ans, sum); } } return ans + frequencyMap.getOrDefault(k, 0); } } ``` ```python [] from collections import defaultdict class Solution: def maxFrequency(self, nums, k): freq_map = defaultdict(int) for num in nums: freq_map[num] += 1 ans = 0 for i in range(1, 51): sum_val = 0 for num in nums: if num == i: sum_val += 1 if num == k: sum_val -= 1 sum_val = max(sum_val, 0) ans = max(ans, sum_val) return ans + freq_map[k] ``` ```javascript [] class Solution { maxFrequency(nums, k) { const freqMap = new Map(); for (const num of nums) { freqMap.set(num, (freqMap.get(num) || 0) + 1); } let ans = 0; for (let i = 1; i <= 50; i++) { let sum = 0; for (const num of nums) { if (num === i) sum++; if (num === k) sum--; if (sum < 0) sum = 0; ans = Math.max(ans, sum); } } return ans + (freqMap.get(k) || 0); } } ```
0
0
['Array', 'Hash Table', 'Math', 'Dynamic Programming', 'Greedy', 'Prefix Sum', 'Python', 'C++', 'Java', 'JavaScript']
0
maximum-frequency-after-subarray-operation
lets View it as a dynammic programming problem which ends at j but in a different way
lets-view-it-as-a-dynammic-programming-p-yxgv
IntuitionIn this problem, we want to maximize the occurrences of k. A key observation is that the same elements will contribute the same value when transformed
aspiringgarv
NORMAL
2025-01-31T06:37:24.242644+00:00
2025-01-31T06:37:24.242644+00:00
4
false
# Intuition In this problem, we want to maximize the occurrences of `k`. A key observation is that the same elements will contribute the same value when transformed into `k`. Thus, we can **group occurrences of the same element** and use these indices as potential start and end points for our subarrays. # Approach ### Step 1: Grouping Transformation Points - Let the required difference be `x = k - a[i]`. - Suppose `x = 8`, and the indices where `a[i] + 8 = k` are `[2, 5, 7, 11, 22]`. - These indices represent positions in the array where elements can be transformed into `k`. ### Step 2: Defining DP State - Let `dp[i]` be the **maximum number of occurrences of `k` in a subarray ending at index `i`**. - Initialize: ```python dp[0] = 1 + pref[occ[0] - 1] ### Step 3: State Transition - Update dp[i] as: - dp[i] = max(pref[i-1] + 1, dp[i-1]) • This ensures we account for: • pref[i-1] + 1: The new occurrence at i • dp[i-1]: Maintaining previous optimal results ### Step 4: Compute the Final Answer - For each dp[i], compute the overall maximum by considering elements after index i. - Maintain: - max1 = max(max1, dp[i] + suff[i+1]) - Here, suff[i+1] counts occurrences of k from index i+1 onward. # Complexity - Time complexity: O((no of distinct elements in array at most 50)*n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int maxFrequency(int[] nums, int k) { int p = 0; int n = nums.length; for (int i = 0; i < nums.length; i++) { if (nums[i] == k) { p++; } } if (p == 0) { HashMap<Integer, Integer> hm = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int x = k - nums[i]; if (hm.containsKey(x)) { hm.put(x, hm.get(x) + 1); } else { hm.put(x, 1); } } int max = 0; for (Map.Entry<Integer, Integer> entry : hm.entrySet()) { max = Math.max(max, entry.getValue()); } return max; } else { int pref[] = new int[n]; pref[0] = nums[0] == k ? 1 : 0; for (int i = 1; i < n; i++) { if (nums[i] == k) { pref[i] = pref[i - 1] + 1; } else { pref[i] = pref[i - 1]; } } int suff[] = new int[n]; suff[n - 1] = nums[n - 1] == k ? 1 : 0; for (int i = n - 2; i >= 0; i--) { if (nums[i] == k) { suff[i] = suff[i + 1] + 1; } else { suff[i] = suff[i + 1]; } } HashMap<Integer, ArrayList<Integer>> hm = new HashMap<>(); for (int i = 0; i < n; i++) { int x = k - nums[i]; if (hm.containsKey(x)) { hm.get(x).add(i); } else { ArrayList<Integer> al = new ArrayList<>(); al.add(i); hm.put(x, al); } } int maxi = 0; for (int j : hm.keySet()) { ArrayList<Integer> a = hm.get(j); int dp[] = new int[a.size()]; dp[0] = 1+(a.get(0)-1>=0?pref[a.get(0)-1]:0); for(int i = 1;i<a.size();i++){ int val = (a.get(i)-1>=0?pref[a.get(i)-1]:0); dp[i] = Math.max(dp[i-1]+1,val+1); } for(int i = 0;i<a.size();i++){ int val = (a.get(i)+1<n?suff[a.get(i)+1]:0); maxi = Math.max(dp[i]+val,maxi); } } return maxi; } } } ```
0
0
['Java']
0
maximum-frequency-after-subarray-operation
Heap Solution | Python
heap-solution-python-by-cholebhature-xbj8
Complexity Time complexity: O(nlogn) Space complexity: O(n) Code
cholebhature
NORMAL
2025-01-30T10:08:16.051076+00:00
2025-01-30T10:08:16.051076+00:00
11
false
# Complexity - Time complexity: $$O(nlogn)$$ - Space complexity: $$O(n)$$ # Code ```python3 [] class Solution: def maxFrequency(self, nums: List[int], k: int) -> int: n = len(nums) t = 0 for i in nums: if i != k: t = 1 break temp = nums.count(k) ans = temp+t l = [] for i in range(51): l.append([]) arr = [] x = 0 for i in range(n): x += nums[i] == k arr.append(x) d = defaultdict(int) for i in range(n): if nums[i] == k: continue d[nums[i]] += 1 right_h = d[nums[i]]-arr[i] if l[nums[i]]: left_h = heappop(l[nums[i]]) ans = max(ans,temp+right_h-left_h+1) heappush(l[nums[i]],left_h) heappush(l[nums[i]],right_h) return ans ```
0
0
['Python3']
0
maximum-frequency-after-subarray-operation
Using simple maximum subarray sum kadence algo
using-simple-maximum-subarray-sum-kadenc-5i0x
Using simple maximum subarray sum kadence algoCode
rthakur2712
NORMAL
2025-01-30T09:58:03.648464+00:00
2025-01-30T09:58:03.648464+00:00
16
false
Using simple maximum subarray sum kadence algo # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& a, int k) { int n = int(a.size()); int m = *max_element(a.begin(), a.end()); int maxi_ans = 0; int cnt=0; for(int i=0; i<n; i++){ if( a[i] == k )cnt++; } for(int i=0; i<=m; i++ ){ if( i == k )continue; int ans = 0; // cout<<"i:"<<i<<"\n"; for(int r=0; r<n; r++){ if( ans < 0 )ans=0; if( a[r] == i ){ ans++; } else if( a[r] == k ){ ans--; } // else no change to answer maxi_ans = max(maxi_ans, ans); // cout<<" r: "<<r<<" ans: "<<ans<<" maxi_ans:"<<maxi_ans<<"\n"; } } return cnt+maxi_ans; } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
Easiest organic approach || O(50*N)
easiest-organic-approach-o50n-by-seriall-btzf
Intuition/ApproachIdea is to first bucketise each partition and calculate the frequency of each number for each bucket. Then run the helper function for each po
seriallazer
NORMAL
2025-01-29T12:21:52.934178+00:00
2025-01-29T12:24:11.530746+00:00
9
false
# Intuition/Approach <!-- Describe your first thoughts on how to solve this problem. --> Idea is to first bucketise each partition and calculate the frequency of each number for each bucket. Then run the helper function for each possible number with this bucketised frequency list to get the subarray that maximises Last step is to find the maximum among all such subarr-max. <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(50*N) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(50*N) , can be easily reduced to O(K), K = frequency of k <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def maxFrequency(self, N: List[int], k: int) -> int: klist = [] D = [[0] for _ in range(51)] for i in range(len(N)): if N[i] == k: klist.append(i) for j in range(51): D[j].append(0) else: D[N[i]][-1] += 1 K = len(klist) def helper(L): lval = L[0] + K mval = lval for i in range(1, len(L)): val = max(L[i]+lval-1, L[i]+K) mval = max(mval, val) lval = val return mval maxval = 0 for i in range(1, 51): maxval = max(maxval, helper(D[i])) return maxval ```
0
0
['Python3']
0
maximum-frequency-after-subarray-operation
Maximum Frequency After Subarray Operation
maximum-frequency-after-subarray-operati-z12e
Code
Ansh1707
NORMAL
2025-01-29T03:35:47.307104+00:00
2025-01-29T03:35:47.307104+00:00
7
false
# Code ```python [] class Solution(object): def maxFrequency(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ original_count = nums.count(k) n = len(nums) def kadane(arr): max_current = max_global = arr[0] for num in arr[1:]: max_current = max(num, max_current + num) max_global = max(max_global, max_current) return max_global contrib_non_candidate = [-1 if a == k else 0 for a in nums] max_gain_non_candidate = kadane(contrib_non_candidate) candidate_x = set(k - a for a in nums) max_gain = max_gain_non_candidate for x in candidate_x: contrib = [] for a in nums: contrib_val = (1 if (a + x == k) else 0) - (1 if a == k else 0) contrib.append(contrib_val) current_max = kadane(contrib) if current_max > max_gain: max_gain = current_max return original_count + max_gain ```
0
0
['Python']
0
maximum-frequency-after-subarray-operation
Kadane's
kadanes-by-srptv-juox
IntuitionApproachComplexity Time complexity: Space complexity: Code
srptv
NORMAL
2025-01-29T02:33:00.081927+00:00
2025-01-29T02:33:00.081927+00:00
8
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def maxFrequency(self, nums: List[int], k: int) -> int: hs = Counter(nums) seen = set(nums) ans = hs[k] for s in seen: cur = 0 mx = 0 for n in nums: if n == s and n == k: continue if s == n: cur += 1 elif n == k: cur -= 1 mx = max(mx, cur) if cur < 0: cur = 0 ans = max(ans, mx + hs[k]) return ans # hs = Counter(nums) # # # print(hs) # e = 0 # a = 0 # for h in hs: # if hs[h] > e and h != k: # a = h # e = hs[h] # # # print(a, e) # n = hs[k] if k in hs else 0 # # return n + e # i = 0 # hs = defaultdict(int) # mx = 0 # el = 0 # while i < len(nums): # if nums[i] == k: # hs = defaultdict(int) # else: # hs[nums[i]] += 1 # if hs[nums[i]] > mx: # mx = hs[nums[i]] # el = nums[i] # i += 1 # # print(el, mx) # return max(e, mx + n) ```
0
0
['Python3']
0
maximum-frequency-after-subarray-operation
Maximum Frequency After Subarray Operations || Java Solution
maximum-frequency-after-subarray-operati-pwkz
IntuitionThe problem for the maximum frequency of any number in the array after potentially modifying some of the values. Modifications can be done by changing
pawan_leel
NORMAL
2025-01-28T18:47:40.267658+00:00
2025-01-28T18:47:40.267658+00:00
14
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem for the maximum frequency of any number in the array after potentially modifying some of the values. Modifications can be done by changing some numbers to the number `k`, which is given. This means that if we can maximize how many times we can change numbers to `k`, we might increase the frequency of `k`. # Approach <!-- Describe your approach to solving the problem. --> 1. **Count Occurrences of k:** First, we count how many times k appears in the array. This will be our base frequency for k 2. **Sliding Window to Maximize Gains:** We then iterate through the array and try to "increase" the frequency of k by modifying other numbers to k. This can be done by using a sliding window to find the maximum "gain" we can get by changing values to k. - The key here is that the sliding window should consider any numbers that can potentially be changed to k and how that changes the frequency. - We need to consider the difference between how many values we can change within a window and whether we can actually afford the changes 3. **Maximize Over All Possible Numbers:** We loop through all possible numbers and try to calculate the maximum frequency of k we can achieve by converting those numbers to k. The overall answer will be the frequency of k plus the maximum "gain" we can achieve through the sliding window process. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> The Time Complexity is $$O(n)$$, where n is the size of array - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> The Space Complexity is $$O(1)$$. # Code ```java [] class Solution { public int maxFrequency(int[] nums, int k) { int totalK =0; for(int num:nums){ if(num==k) totalK++; } int maxGain = 0; for (int v = 1; v <= 50; v++) { if (v == k) continue; int currentSum = 0; int localMax = 0; for (int num : nums) { if (num == v) { currentSum += 1; } else if (num == k) { currentSum -= 1; } if (currentSum < 0) { currentSum = 0; } localMax = Math.max(localMax, currentSum); } maxGain = Math.max(maxGain, localMax); } return totalK + maxGain; } } ```
0
0
['Java']
0
maximum-frequency-after-subarray-operation
dynamic programming || prefix map|| suffix map || o(n*50) ||c ++
dynamic-programming-prefix-map-suffix-ma-s6ow
IntuitionApproachComplexity Time complexity: Space complexity: Code
sarthakrautelanew
NORMAL
2025-01-28T17:13:52.815194+00:00
2025-01-28T17:13:52.815194+00:00
33
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int solve(int idx,int last,vector<int>&nums,vector<int>&pre,vector<int>&suff,vector<vector<int>>&dp){ if(idx==nums.size()) return 0; if(dp[idx][last]!=-1) return dp[idx][last]; int ans=0; if(last==0){ ans=max(ans,solve(idx+1,last,nums,pre,suff,dp)); ans=max(ans,pre[idx]+solve(idx+1,nums[idx],nums,pre,suff,dp)+1); } else{ ans=max(ans,solve(idx+1,last,nums,pre,suff,dp)+(int)(nums[idx]==last)); ans=max(ans,suff[idx]); } return dp[idx][last]=ans; } int maxFrequency(vector<int>& nums, int k) { int n=nums.size(); vector<int>pre(n+1,0); vector<int>suff(n+1,0); int maxi=-1; for(int i=0;i<n;i++){ maxi=max(nums[i],maxi); pre[i+1]+=pre[i]+ (nums[i]==k); int y=n-i-1; suff[y]+=suff[y+1]+ (nums[y]==k); } vector<vector<int>>dp(n,vector<int>(maxi+1,-1)); return solve(0,0,nums,pre,suff,dp); } }; ```
0
0
['Dynamic Programming', 'C++']
0
maximum-frequency-after-subarray-operation
Simple Java Solution
simple-java-solution-by-sakshikishore-6rrl
Code
sakshikishore
NORMAL
2025-01-28T12:21:06.409452+00:00
2025-01-28T12:21:06.409452+00:00
12
false
# Code ```java [] class Solution { public int maxFrequency(int[] nums, int k) { int pref[] = new int[nums.length]; int sum = 0; HashSet<Integer> hset = new HashSet<Integer>(); for (int i = 0; i < nums.length; i++) { if (nums[i] == k) { sum += 1; } else { hset.add(nums[i]); } pref[i] = sum; } if (sum == nums.length) { return sum; } int max = sum + 1; Iterator<Integer> itr = hset.iterator(); while (itr.hasNext()) { int x = itr.next(); int j = 0; while (nums[j] != x) { j++; } Queue<Integer> q = new LinkedList<Integer>(); q.add(j); j++; while (j < nums.length) { if (nums[j] == x) { if (q.peek() == 0) { if (pref[j] >= q.size() + 1) { q.poll(); if (q.size() > 0) { int t = q.peek(); while (q.size() > 0 && pref[j] - pref[t - 1] >= q.size() + 1) { q.poll(); if (q.size() > 0) { t = q.peek(); } } q.add(j); if (q.size() + sum - (pref[j] - pref[t - 1]) > max) { max = q.size() + sum - (pref[j] - pref[t - 1]); } } else { q.add(j); } } else { q.add(j); if (q.size() + sum - pref[j] > max) { max = q.size() + sum - pref[j]; } } } else { int t = q.peek(); while (q.size() > 0 && pref[j] - pref[t - 1] >= q.size() + 1) { q.poll(); if (q.size() > 0) { t = q.peek(); } } q.add(j); if (q.size() + sum - (pref[j] - pref[t - 1]) > max) { max = q.size() + sum - (pref[j] - pref[t - 1]); } } } j++; } } return max; } } ```
0
0
['Java']
0
maximum-frequency-after-subarray-operation
memoisation for each valid x
memoisation-for-each-valid-x-by-joshuadl-075c
Intuitionstatus: 0, 1, 2 0 -> we havent taken a subarray yet => we can either continue without taking or decide to take it from this index.1 -> we are currently
joshuadlima
NORMAL
2025-01-28T12:19:42.670076+00:00
2025-01-28T13:10:37.587177+00:00
4
false
# Intuition status: 0, 1, 2 0 -> we havent taken a subarray yet => we can either continue without taking or decide to take it from this index. 1 -> we are currently taking a subarray => we can either continue taking the subarray or stop taking it. 2 -> we have completed the subarray => we can only go on since only one subarray is allowed. # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n * 3 * 100) - Space complexity: O(n * 3 * 100) # Code ```cpp [] int dp[100001][3][101]; class Solution { public: int bruteforce(int ix, int status, int x, int k, vector<int>& nums) { if(dp[ix][status][x + 50] == -1){ if(ix == nums.size()) return 0; int a1 = 0, a2 = 0; if(status == 0) { // not yet started // start a1 = (nums[ix] + x == k) + bruteforce(ix + 1, 1, x, k, nums); // dont start a2 = (nums[ix] == k) + bruteforce(ix + 1, 0, x, k, nums); } else if (status == 1) { // started // go on a1 = (nums[ix] + x == k) + bruteforce(ix + 1, 1, x, k, nums); // stop a2 = (nums[ix] == k) + bruteforce(ix + 1, 2, x, k, nums); } else { // ended a1 = (nums[ix] == k) + bruteforce(ix + 1, 2, x, k, nums); a2 = a1; } dp[ix][status][x + 50] = max(a1, a2); } return dp[ix][status][x + 50]; } int maxFrequency(vector<int>& nums, int k) { // init for(int i = 0; i <= nums.size(); i++) memset(dp[i], -1, sizeof(dp[i])); int mn = INT_MAX, mx = INT_MIN; for(auto it : nums) mn = min(mn, it), mx = max(mx, it); int ans = 0; for(int x = k - mx; x <= k - mn; x++) { ans = max(ans, bruteforce(0, 0, x, k, nums)); } return ans; } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
modified Kadane's algo.
modified-kadanes-algo-by-rishiinsane-in3h
IntuitionWe need to maximize the frequency of any element in the array after transforming some occurrences of the given element k into other values. Observe tha
RishiINSANE
NORMAL
2025-01-28T09:49:31.822209+00:00
2025-01-28T09:49:31.822209+00:00
18
false
# Intuition We need to maximize the frequency of any element in the array after transforming some occurrences of the given element k into other values. Observe that the transformation from k to any other element can be thought of as a sliding window or subarray problem, where we try to accumulate the maximum possible number of transformations while maximizing the frequency of the transformed element. The transformation's impact on the frequency of the target element is tracked by adjusting counts, and we want to find the most beneficial transformations. --- # Approach Count the initial occurrences of \(k\) in the array (`baseCnt`). Then, it iterates through all potential target values (from 1 to 50) to explore the possibility of transforming \(k\) into each of these values. For each target, it calculates the maximum number of valid transformations that can occur by counting the contributions of each element in the array. It increments the count when an element matches the target value and decrements it when encountering \(k\) (since transforming \(k\) into the target value is a gain). The subarray count (`curCnt`) is reset when it becomes negative, ensuring that only beneficial transformations are considered. The result is the sum of the original count of \(k\) and the maximum frequency gain obtained from these transformations. # Complexity - Time complexity: O(n) - Space complexity: O(1) # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int baseCnt = count(nums.begin(), nums.end(), k); int maxCnt = 0; for (int target = 1; target <= 50; ++target) { if (target == k) continue; int curCnt = 0, maxCur = 0; for (int num : nums) { curCnt += (num == target) ? 1 : (num == k ? -1 : 0); curCnt = max(curCnt, 0); maxCur = max(maxCur, curCnt); } maxCnt = max(maxCnt, maxCur); } return baseCnt + maxCnt; } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
Simple Kadane Algorithms
simple-kadane-algorithms-by-dnanper-64hp
IntuitionApproachComplexity Time complexity: Space complexity: Code
dnanper
NORMAL
2025-01-28T07:09:33.903771+00:00
2025-01-28T07:09:33.903771+00:00
7
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int all = 0; for (auto &x:nums) all += (x==k); // cout << "all " << all << endl; int res = 0, n = nums.size(); for (int h = k-50; h <= k; h++) { int x = k-h; // cout << "x " << x << endl; if (x == k) continue; int cur = 0, ans = 0; for (int a : nums) { cur += (a == x ? 1 : (a == k ? -1 : 0)); cur = max(cur, 0); ans = max(ans, cur); } res = max(res, ans); } return all + res; } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
Brute Force for all possible addition of the values -> bound [-49, 49]
brute-force-for-all-possible-addition-of-qitp
IntuitionSimply using the Kadane's Algorithms find the maximum sum of the subarray after the array modification. Rest is in the code you can refer it i am feeli
Shivam_Kapoor
NORMAL
2025-01-28T07:06:06.974654+00:00
2025-01-28T07:06:06.974654+00:00
6
false
# Intuition Simply using the Kadane's Algorithms find the maximum sum of the subarray after the array modification. Rest is in the code you can refer it i am feeling a little sleepy # Complexity - Time complexity: O(98 * N) ~ O(N) - Space complexity: O(98 * N) ~ O(N) # Code ```cpp [] #define ll long long class Solution { public: int maxFrequency(vector<int>& nums, int k) { ll n = nums.size(); ll ans = 0; for(ll i = 0; i < n; i++){ if(nums[i] == k) ans++; } // cout << "ARRAY is : " << endl; // for(ll i = 0; i < n; i++){ // cout << nums[i] << " "; // }cout << endl; ll xx = 0; for(ll i = 0; i < n; i++){ if(nums[i] == k) xx++; } for(ll i = -49; i <= 49; i++){ if(i == 0) continue; vector<ll> y; for(ll j = 0; j < n; j++){ if(nums[j] + i == k) y.push_back(1); else if(nums[j] == k) y.push_back(-1); else y.push_back(0); } // Now i need to find the largest subarray sum ll num_pos = 0; ll num_neg = 0; ll maxi = 0; ll mini = 0; ll cnt = 0; ll max_sum = 0; for(ll j = 0; j < n; j++){ if(y[j] == 1){ num_pos++; cnt++; } if(y[j] == -1){ num_neg++; cnt--; } if(cnt > max_sum){ maxi = num_pos; mini = num_neg; max_sum = cnt; } if(cnt < 0){ cnt = 0; num_pos = 0; num_neg = 0; } } ll add = maxi; ll add1 = xx - mini; ans = max(ans, add + add1); } return ans; } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
Max Subarray Sum || Kadane's Algorithm
max-subarray-sum-kadanes-algorithm-by-ar-dgrn
IntuitionThe important observation to make is that nums can be divided into two parts: one part containing values i that can be incremented to k, and one part t
arthurcorrell
NORMAL
2025-01-27T21:18:34.375129+00:00
2025-01-27T21:18:34.375129+00:00
19
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The important observation to make is that $nums$ can be divided into two parts: one part containing values $i$ that can be incremented to $k$, and one part that contains $k$. For a certain number $i$ and a certain subdivision of the array into two parts, the sum of all occurences of $i$ and $k$ is maximal # Approach <!-- Describe your approach to solving the problem. --> #### Part 1 (Inner loop) Assuming we have a value $i$, we can count the longest 'streak' of $i$ in $nums$, saving it to a 'max' value. Each value of $k$ disrupting this streak decrements one from our count. If there are more $k$ than $i$ in a 'streak', there is a net loss, as performing the operation on this subarray would convert $k$ to another number more often than it would convert $i$ to $k$. When the streak reaches this point, it is simply reset. #### Part 2 (Outer Loop) We perform the operation from part 1 for each possible value $i$. It only makes sense for $i$ to assume values from $nums$, so we iterate over all unique values in $nums$. This approach is a version of kadane's algorithm. In kadane's algorithm, the array is iterated over and the longest subarray sum updated with each iteration. If the longest subarray becomes less than 0, the subarray up to the current point of iteration cannot be part of the final subarray, as its net contribution is <= 0. However, the longest subarray until that point is already saved in a global variable # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> Since there can be atmost 50 unique values in nums (see problem constraints) $$O(50*n) --> O(n)$$ Time complexity is proportional to input $n$ times a constant - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> $$O(1)$$ # Code ```python3 [] class Solution: def maxFrequency(self, nums: List[int], k: int) -> int: global_max = 0 kc = nums.count(k) a = set(nums) for i in a: local_max = 0 c = 0 for num in nums: if num == i: c += 1 if num == k : c-= 1 c = max(c, 0) local_max = max(local_max, c) global_max = max(local_max, global_max) return global_max + kc ```
0
0
['Python3']
0
maximum-frequency-after-subarray-operation
Original approach without using Kadane CPP solution
original-approach-without-using-kadane-c-pct6
IntuitionApproachFor every target value in the array we can greedily find the maximum freq of k restricting subarray selection upto index i and utilizing postfi
Susm
NORMAL
2025-01-27T20:07:26.687730+00:00
2025-01-28T07:00:15.022530+00:00
9
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach For every target value in the array we can greedily find the maximum freq of k restricting subarray selection upto index i and utilizing postfixsum of remaining k's on its right. # Complexity - Time complexity: O(N*M) - Space complexity: O(N) # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int l=*min_element(nums.begin(),nums.end()), r=*max_element(nums.begin(),nums.end()),n=nums.size(); vector<int> kcount(n,0); for(int i=n-1;i>=0;--i){ kcount[i]=(nums[i]==k) + (i<n-1 ? kcount[i+1] : 0); } int max_freq=kcount[0]; for(int i=l;i<=r;++i) { int curr=0,kc=0; for(int j=0;j<n;++j){ if(nums[j]==i) curr++; else if(nums[j]==k){ max_freq=max(max_freq,curr+kcount[j]); while(j<n&&nums[j]==k){ kc++; j++; } if(curr<kc) curr=kc; j--; } } max_freq=max(max_freq,curr); } return max_freq; } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
Short and elegant solution||Self-commented code
short-and-elegant-solutionself-commented-ydo8
Code
andrjob
NORMAL
2025-01-27T16:45:55.953433+00:00
2025-01-27T16:45:55.953433+00:00
8
false
# Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { array<int, 51> freq = {}; int result = 0; int count = 0; for (int num : nums) { freq[num] = max(freq[num], count) + 1; if (num == k) { ++result; ++count; } result = max(result, freq[num]); } return result; } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
JAVA|
java-by-tanishak07-n1o8
IntuitionApproachComplexity Time complexity: Space complexity: Code
tanishak07
NORMAL
2025-01-27T16:20:44.881300+00:00
2025-01-27T16:20:44.881300+00:00
10
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ -->O(1) # Code ```java [] class Solution { public int maxFrequency(int[] nums, int k) { int freq[]=new int[51]; Arrays.fill(freq,0); for(int i : nums ) { freq[i]++; } int count=0,maxi=0; count+=freq[k]; if(count==nums.length) { return nums.length; } for(int i=1;i<freq.length;i++) { if(i==k) continue; int current = 0, maxCurrent = 0; for (int num : nums) { current += (num == i) ? 1 : (num == k) ? -1 : 0; current = Math.max(current, 0); maxCurrent = Math.max(maxCurrent, current); } maxi=Math.max(maxi,maxCurrent); } return count+maxi; } } ```
0
0
['Prefix Sum', 'Java']
0
maximum-frequency-after-subarray-operation
Kadans alogo
kadans-alogo-by-madhavendrasinh44-2568
IntuitionLets use kadens algorithmApproachFirst find the frequency of all the element and then check for all the element in the map that who is most occuring in
Madhavendrasinh44
NORMAL
2025-01-27T16:08:25.581378+00:00
2025-01-27T16:08:25.581378+00:00
25
false
# Intuition Lets use kadens algorithm # Approach First find the frequency of all the element and then check for all the element in the map that who is most occuring in all the subarray. # Complexity - Time complexity: $$O(n)$$ - Space complexity: $$O(n)$$ # Code ```cpp [] class Solution { public: int check(vector<int>&nums, int val,int k) { int maxi=0; int total=0; for(int i =0;i<nums.size();i++) { if(nums[i]==k) { total=total-1; } if(nums[i]==val){ total=total+1; } if(total<0)total=0; maxi=max(maxi,total); } return maxi; } int maxFrequency(vector<int>& nums, int k) { unordered_map<int,int>mp; for(int it : nums){ mp[it]++; } int maxfre=0; for(auto it : mp) { int val=it.first; maxfre=max(maxfre,check(nums,val,k)); } return maxfre+mp[k]; } }; ```
0
0
['Hash Table', 'Prefix Sum', 'C++']
0
maximum-frequency-after-subarray-operation
[CODE ONLY][DEBUG OUTPUT] PYTHON USING Lee's SOLUTION
code-onlydebug-output-python-using-lees-cfb17
USING lee's solutionLINK: https://leetcode.com/problems/maximum-frequency-after-subarray-operation/solutions/6329937/java-c-python-kadaneDEBUG OUTPUTCode
greg_savage
NORMAL
2025-01-27T15:39:11.083037+00:00
2025-01-27T15:39:11.083037+00:00
9
false
# USING lee's solution # LINK: https://leetcode.com/problems/maximum-frequency-after-subarray-operation/solutions/6329937/java-c-python-kadane # DEBUG OUTPUT ``` DEBUG OUTPUT Input nums = [1,2,3,4,5,6] k = 1 Stdout keys_to_freq are... keys: 1, frequency: 1 keys: 2, frequency: 1 keys: 3, frequency: 1 keys: 4, frequency: 1 keys: 5, frequency: 1 keys: 6, frequency: 1 looking for freq's of 1... looking at 1... subtotal=0, current=0 looking at 2... subtotal=0, current=0 looking at 3... subtotal=0, current=0 looking at 4... subtotal=0, current=0 looking at 5... subtotal=0, current=0 looking at 6... subtotal=0, current=0 BEST: 0 looking for freq's of 2... looking at 1... subtotal=0, current=0 looking at 2... subtotal=0, current=1 looking at 3... subtotal=1, current=1 looking at 4... subtotal=1, current=1 looking at 5... subtotal=1, current=1 looking at 6... subtotal=1, current=1 BEST: 1 looking for freq's of 3... looking at 1... subtotal=0, current=0 looking at 2... subtotal=0, current=0 looking at 3... subtotal=0, current=1 looking at 4... subtotal=1, current=1 looking at 5... subtotal=1, current=1 looking at 6... subtotal=1, current=1 BEST: 1 looking for freq's of 4... looking at 1... subtotal=0, current=0 looking at 2... subtotal=0, current=0 looking at 3... subtotal=0, current=0 looking at 4... subtotal=0, current=1 looking at 5... subtotal=1, current=1 looking at 6... subtotal=1, current=1 BEST: 1 looking for freq's of 5... looking at 1... subtotal=0, current=0 looking at 2... subtotal=0, current=0 looking at 3... subtotal=0, current=0 looking at 4... subtotal=0, current=0 looking at 5... subtotal=0, current=1 looking at 6... subtotal=1, current=1 BEST: 1 looking for freq's of 6... looking at 1... subtotal=0, current=0 looking at 2... subtotal=0, current=0 looking at 3... subtotal=0, current=0 looking at 4... subtotal=0, current=0 looking at 5... subtotal=0, current=0 looking at 6... subtotal=0, current=1 BEST: 1 k occurs 1 times... and best operatoin is 1... ``` # Code ```python3 [] # USING lee's solution # LINK: https://leetcode.com/problems/maximum-frequency-after-subarray-operation/solutions/6329937/java-c-python-kadane from collections import Counter class Solution: def maxFrequency(self, nums: List[int], k: int) -> int: keys_to_freq = Counter(nums) # print(f'keys_to_freq are...') # for each_key, each_freq in keys_to_freq.items(): # print(f'keys: {each_key}, frequency: {each_freq}') def kadane(target_value: int) -> int: subtotal = 0 current = 0 # print(f'\tlooking for freq\'s of {target_value}...') for each_number in nums: if each_number == k: current -= 1 if each_number == target_value: current += 1 if current < 0: current = 0 # print(f'\t\tlooking at {each_number}... subtotal={subtotal}, current={current}') subtotal = max(subtotal, current) # print(f'\t\t\tBEST: {subtotal}') return subtotal all_best_operations = [kadane(each_target) for each_target in keys_to_freq.keys()] k_count = keys_to_freq[k] # print(f'k occurs {k_count} times... and best operatoin is {max(all_best_operations)}...') return max(all_best_operations) + k_count # DEBUG OUTPUT # Input # nums = # [1,2,3,4,5,6] # k = # 1 # Stdout # keys_to_freq are... # keys: 1, frequency: 1 # keys: 2, frequency: 1 # keys: 3, frequency: 1 # keys: 4, frequency: 1 # keys: 5, frequency: 1 # keys: 6, frequency: 1 # looking for freq's of 1... # looking at 1... subtotal=0, current=0 # looking at 2... subtotal=0, current=0 # looking at 3... subtotal=0, current=0 # looking at 4... subtotal=0, current=0 # looking at 5... subtotal=0, current=0 # looking at 6... subtotal=0, current=0 # BEST: 0 # looking for freq's of 2... # looking at 1... subtotal=0, current=0 # looking at 2... subtotal=0, current=1 # looking at 3... subtotal=1, current=1 # looking at 4... subtotal=1, current=1 # looking at 5... subtotal=1, current=1 # looking at 6... subtotal=1, current=1 # BEST: 1 # looking for freq's of 3... # looking at 1... subtotal=0, current=0 # looking at 2... subtotal=0, current=0 # looking at 3... subtotal=0, current=1 # looking at 4... subtotal=1, current=1 # looking at 5... subtotal=1, current=1 # looking at 6... subtotal=1, current=1 # BEST: 1 # looking for freq's of 4... # looking at 1... subtotal=0, current=0 # looking at 2... subtotal=0, current=0 # looking at 3... subtotal=0, current=0 # looking at 4... subtotal=0, current=1 # looking at 5... subtotal=1, current=1 # looking at 6... subtotal=1, current=1 # BEST: 1 # looking for freq's of 5... # looking at 1... subtotal=0, current=0 # looking at 2... subtotal=0, current=0 # looking at 3... subtotal=0, current=0 # looking at 4... subtotal=0, current=0 # looking at 5... subtotal=0, current=1 # looking at 6... subtotal=1, current=1 # BEST: 1 # looking for freq's of 6... # looking at 1... subtotal=0, current=0 # looking at 2... subtotal=0, current=0 # looking at 3... subtotal=0, current=0 # looking at 4... subtotal=0, current=0 # looking at 5... subtotal=0, current=0 # looking at 6... subtotal=0, current=1 # BEST: 1 # k occurs 1 times... and best operatoin is 1... ```
0
0
['Python3']
0
maximum-frequency-after-subarray-operation
[JavaScript] Easy & Fast DP Solution
javascript-easy-fast-dp-solution-by-liew-bzu7
IntuitionApproachComplexity Time complexity: Space complexity: Code
liew-li
NORMAL
2025-01-27T12:28:31.090325+00:00
2025-01-27T12:28:31.090325+00:00
16
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {number[]} nums * @param {number} k * @return {number} */ var maxFrequency = function(nums, k) { let k_cnt_map = new Array(nums.length + 1).fill(0); let total_k = 0; const dp = {}; const map = {}; for (let i = 0; i < nums.length; ++i) { total_k += (nums[i] == k ? 1 : 0); k_cnt_map[i+1] = total_k; } let res = total_k; for (let i = 0; i < nums.length; ++i) { const d = (nums[i] == k ? 0 : 1); if (nums[i] in map) { const last = map[nums[i]]; dp[nums[i]] = Math.max(total_k + d, dp[nums[i]] + d - (k_cnt_map[i+1] - k_cnt_map[last])); } else { dp[nums[i]] = total_k + d; } map[nums[i]] = i; res = Math.max(res, dp[nums[i]]); } return res; }; ```
0
0
['JavaScript']
0
maximum-frequency-after-subarray-operation
Java solution using recursion
java-solution-using-recursion-by-karthi_-bg1w
ApproachCount Occurrences: Use a recursive method to count the total occurrences of k in the array.Recursive Frequency Calculation: Use a recursive function to
KARTHI_SARAVANAN_T
NORMAL
2025-01-27T10:29:59.561485+00:00
2025-01-27T10:29:59.561485+00:00
12
false
# Approach **Count Occurrences:** Use a recursive method to count the total occurrences of k in the array. **Recursive Frequency Calculation:** Use a recursive function to iterate through the array, updating frequency counts and keeping track of the maximum frequency achievable by changing elements to k. # Complexity - Time complexity:𝑂(𝑛) - Space complexity:𝑂(1) # Code ```java [] class Solution { public int maxFrequency(int[] nums, int k) { int totalK = countK(nums, k, 0); return maxFrequencyRecursive(nums, k, totalK, 0, 0, new int[51], new int[51]); } private int countK(int[] nums, int k, int index) { if (index == nums.length) return 0; return (nums[index] == k ? 1 : 0) + countK(nums, k, index + 1); } private int maxFrequencyRecursive(int[] nums, int k, int totalK, int prefixCountK, int index, int[] freq, int[] maxval) { if (index == nums.length) return 0; int n = nums[index]; maxval[n] = Math.max(maxval[n], prefixCountK - freq[n]); prefixCountK += (n == k ? 1 : 0); freq[n]++; int res = Math.max((totalK - prefixCountK) + maxval[n] + freq[n], maxFrequencyRecursive(nums, k, totalK, prefixCountK, index + 1, freq, maxval)); return res; } } ```
0
0
['Java']
0
maximum-frequency-after-subarray-operation
Simple Greedy
simple-greedy-by-eskandar1-qtr6
Complexity Time complexity: O(n) Space complexity: O(1)Code
Eskandar1
NORMAL
2025-01-26T21:55:18.153561+00:00
2025-01-26T21:55:51.475735+00:00
60
false
# Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n) -- - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1) --- # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int countK = count(nums.begin(), nums.end(), k); int ans = 0; for(int i=1; i<51; i++){ if(i==k) continue; int tmp=0, res=0, cnt=0; for(int x: nums){ if(x==k) cnt += (cnt+1>tmp) ? 0 : 1; if(x==i) tmp++; res = max(res, tmp-cnt); } ans = max(ans, res); } return ans +=countK; } }; ``` ```java [] class Solution { public int maxFrequency(int[] nums, int k) { int countK = 0, ans = 0; for(int it: nums) countK +=(it==k) ?1 : 0; for(int i=1; i<51; i++){ if(i==k) continue; int tmp=0, res=0, cnt=0; for(int x: nums){ if(x==k) cnt += (cnt+1>tmp) ? 0 : 1; if(x==i) tmp++; res = Math.max(res, tmp-cnt); } ans = Math.max(ans, res); } return ans +=countK; } } ```
0
0
['Array', 'Math', 'Dynamic Programming', 'Greedy', 'C++', 'Java']
0
maximum-frequency-after-subarray-operation
Dynamic Programming Recursive Memoization
dynamic-programming-recursive-memoizatio-8rc4
IntuitionAs the constraints on k is small i thought of using dpApproachRecursive Function (recur):The function explores the possibility of transforming elements
esh_war12
NORMAL
2025-01-26T21:29:32.968808+00:00
2025-01-26T21:29:32.968808+00:00
57
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> As the constraints on k is small i thought of using dp # Approach <!-- Describe your approach to solving the problem. --> Recursive Function (recur): The function explores the possibility of transforming elements in nums to equal k by adding x to them. Tracks three states: index: Current position in the array. x: The number we need to add to some elements to make them equal k. op: Operation state: 0: Operation not started (deciding whether to start). 1: Operation ongoing (continuing to add x). 2: Operation stopped (no further additions allowed). Uses recursion to explore all possible operations and returns the maximum frequency of k. Dynamic Programming: A dp[index][op] table stores results for subproblems defined by the current index and operation state (op) to avoid redundant calculations. Main Function (maxFrequency): Loops through the array and calculates x as the difference between k and nums[i] (i.e., x = k - nums[i]). Uses a map to skip redundant calculations for the same x. Calls the recur function for each valid x and updates the maximum frequency of k. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n*50) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(n*50) # Code ```cpp [] class Solution { public: int n; int dp[100005][3]; vector<int> nums; int recur(int index, int x, int op, int k) { if (index == n) { return 0; } int ans = 0; if (dp[index][op] != -1) { return dp[index][op]; } if (op == 0 || op == 1) { if (op == 0) { // Start now if (nums[index] + x == k) { ans = max(ans, 1 + recur(index + 1, x, 1, k)); } else { ans = max(ans, recur(index + 1, x, 1, k)); } // Or continue with the same if (nums[index] == k) { ans = max(ans, 1 + recur(index + 1, x, op, k)); } else { ans = max(ans, recur(index + 1, x, op, k)); } } else { // Operation started, so if (nums[index] + x == k) { ans = max(ans, 1 + recur(index + 1, x, op, k)); } else { ans = max(ans, recur(index + 1, x, op, k)); } // Or stop the operation if (nums[index] == k) { ans = max(ans, 1 + recur(index + 1, x, 2, k)); } else { ans = max(ans, recur(index + 1, x, 2, k)); } } } else { if (nums[index] == k) { ans = max(ans, 1 + recur(index + 1, x, op, k)); } else { ans = max(ans, recur(index + 1, x, op, k)); } } return dp[index][op] = ans; } int maxFrequency(vector<int>& nums, int k) { this->nums = nums; n = nums.size(); int ans = 0; map<int, int> mp; for (int i = 0; i < n; i++) { int x = k - nums[i]; if (mp.find(x) == mp.end()) { memset(dp, -1, sizeof(dp)); mp[x] = 1; ans = max(ans, recur(0, x, 0, k)); } else { continue; } } return ans; } }; ```
0
0
['Dynamic Programming', 'C++']
0
maximum-frequency-after-subarray-operation
Simple Kidane's algorithm solution | O(n*50) time and O(1) space
simple-kidanes-algorithm-solution-on50-t-bw02
IntuitionApproachComplexity Time complexity: O(n∗50) Space complexity: O(1) Code
sachin_kashi
NORMAL
2025-01-26T18:49:06.426382+00:00
2025-01-26T18:49:06.426382+00:00
16
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: $$O(n*50)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(1)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { // Count how many times the value 'k' appears in the array int cntK = 0; for (auto a : nums) { if (a == k) cntK++; } // Initialize the maximum frequency answer with the count of 'k' int maxAns = cntK; // Iterate through all possible values from 1 to 50 for (int i = 1; i <= 50; i++) { int cur = 0; // Variable to keep track of current frequency adjustment // Traverse the array to compute the adjusted frequency for the current value 'i' for (auto a : nums) { if (a == k) { // If the current element equals 'k', decrement 'cur' cur--; // Ensure 'cur' doesn't go below 0 if (cur < 0) cur = 0; } else if (a == i) { // If the current element equals 'i', increment 'cur' cur++; } // Update the maximum answer with the sum of 'cur' and 'cntK' maxAns = max(maxAns, cur + cntK); } } // Return the maximum frequency found return maxAns; } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
Finally done !! Never thought about kadane this way.
finally-done-never-thought-about-kadane-vekka
After grinding hard and going through several submissions, I got this. Feel free to share your views on my approach.Code
D_Neeraj_Dattu
NORMAL
2025-01-26T18:11:13.820314+00:00
2025-01-26T18:11:13.820314+00:00
21
false
After grinding hard and going through several submissions, I got this. Feel free to share your views on my approach. # Code ```cpp [] class Solution { public: int solve(vector<int> &v1, vector<int> &v2) { int n = v1.size() + v2.size(); vector<int> v(n, -1); int i = 0, j = 0, k = 0; while(i < v1.size() && j < v2.size()) { if(v1[i] < v2[j]) { i++; k++; } else { v[k++] = 1; j++; } } while(j < v2.size()) { v[k++] = 1; j++; } int maxGain = 0, currentGain = 0; for (int i = 0; i < n; i++) { // cout << v[i] << " "; currentGain = max(v[i], currentGain + v[i]); maxGain = max(maxGain, currentGain); } return v1.size() + maxGain; } int maxFrequency(vector<int>& nums, int k) { int n = nums.size(); vector<int> v(n); for(int i = 0; i < n; i++) { v[i] = k - nums[i]; } unordered_map<int, vector<int>> u; int maxFreq = 0; for(int i = 0; i < n; i++) { u[v[i]].push_back(i); int size = u[v[i]].size(); maxFreq = max(maxFreq, size); } if(!u.count(0) || (u.count(0) && u.size() == 1)) { return maxFreq; } maxFreq = 0; vector<int> v0 = u[0]; u.erase(0); for(auto i : u) { // cout << i.first << " -> "; int curr = solve(v0, i.second); // cout << endl; maxFreq = max(maxFreq, curr); } return maxFreq; } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
[Javascript] Kadane`s Algorithm O(50 * n) / O(1)
javascript-kadanes-algorithm-o50-n-o1-by-mm85
Code
_savely
NORMAL
2025-01-26T16:32:51.075771+00:00
2025-01-26T16:32:51.075771+00:00
22
false
# Code ```javascript [] /** * @param {number[]} nums * @param {number} k * @return {number} */ var maxFrequency = function(nums, k) { const kadane = (n, m) => { let count = 0, max = 0; for(const num of nums) { count += num === n ? 1 : 0; max = Math.max(max, count); count -= num === m ? 1 : 0; count = Math.max(0, count); } return max; } const unique = new Set(nums); const countK = unique.has(k) ? kadane(k, 0) : 0; unique.delete(k); let max = 0; for(const n of unique) { max = Math.max(max, kadane(n, k)); } return countK + max; }; ```
0
0
['Array', 'Dynamic Programming', 'Greedy', 'Prefix Sum', 'JavaScript']
0
maximum-frequency-after-subarray-operation
SImple solution using prefix sum
simple-solution-using-prefix-sum-by-risa-mfqa
null
risabhuchiha
NORMAL
2025-01-26T15:29:38.258911+00:00
2025-01-26T15:29:38.258911+00:00
29
false
```java [] class Solution { public int maxFrequency(int[] nums, int k) { HashSet<Integer>hs=new HashSet<>(); int c=0; int ans=0; for(int i:nums){ hs.add(i); if(i==k)c++; } ans=0; for(int j=1;j<=50;j++){ int s=0; int r=0; if(j==k)continue; for(int i=0;i<nums.length;i++){ if(nums[i]==j){ s+=1; } else if(nums[i]==k)s-=1; if(s<0)s=0; r=Math.max(s,r); } ans=Math.max(ans,r); } return ans+c; } } ```
0
0
['Java']
0
maximum-frequency-after-subarray-operation
Optimized Kadane
optimized-kadane-by-devbabbar7-xwcw
IntuitionWe don't need to iterate over all 50 values we can just iterate over the values present in the nums array. I could decrease the runtime for 5800 ms (fa
devbabbar7
NORMAL
2025-01-26T14:31:30.224434+00:00
2025-01-26T14:31:30.224434+00:00
21
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> We don't need to iterate over all 50 values we can just iterate over the values present in the nums array. I could decrease the runtime for 5800 ms (faster than 100%) to 2800 ms. # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def maxFrequency(self, nums: List[int], k: int) -> int: orig = nums.count(k) max_gain = 0 a = set(nums) a.discard(k) for m in a: current = 0 for num in nums: if num == m: current += 1 elif num == k: current -= 1 current = max(current, 0) max_gain = max(max_gain, current) return orig + max_gain ```
0
0
['Python3']
0
maximum-frequency-after-subarray-operation
Kadane Based Solution
kadane-based-solution-by-_leviathan-6630
Code
_Leviathan_
NORMAL
2025-01-26T14:30:01.346642+00:00
2025-01-26T14:30:01.346642+00:00
17
false
# Code ```cpp [] class Solution { public: int search(int curr,vector<int>& nums,int k){ int tot=0; int j=0; int ans=0; for(int i=0;i<nums.size();i++){ if(nums[i]==curr){ tot++; }else if(nums[i]==k){ tot--; } if(tot<0){ while(tot<0){ if(nums[j]==curr){ tot--; } if(nums[j]==k){ tot++; } j++; } }else{ ans=max(ans,tot); } } return ans; } int maxFrequency(vector<int>& nums, int k) { int zero=0; for(int i=0;i<nums.size();i++){ if(nums[i]==k){ zero++; } } int z=0; int ans=0; for(int i=0;i<51;i++){ if(i!=k){ ans=max(ans,search(i,nums,k)); } } return ans+zero; } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
My Solutions
my-solutions-by-hope_ma-0398
1. Use the Kadane Algorithm2. Use the DP3. Use the same idea as 2 with the more efficient time complexity
hope_ma
NORMAL
2025-01-26T14:02:31.564174+00:00
2025-01-26T14:02:31.564174+00:00
11
false
**1. Use the `Kadane` Algorithm** ``` /** * Time Complexity: O(n * num_range) * Space Complexity: O(num_range) * where `n` is the length of the vector `nums` * `num_range` is (`max_num` - `min_num` + 1) * `max_num` is the maximum number of the vector `nums` * `min_num` is the minimum number of the vector `nums` */ class Solution { public: int maxFrequency(const vector<int> &nums, const int k) { const auto mm = minmax_element(nums.begin(), nums.end()); const int min_num = min(*mm.first, k); const int max_num = max(*mm.second, k); const int num_range = max_num - min_num + 1; int num_to_count[num_range]; memset(num_to_count, 0, sizeof(num_to_count)); for (const int num : nums) { ++num_to_count[num - min_num]; } int max_count = 0; for (int num = min_num; num < max_num + 1; ++num) { if (num != k && num_to_count[num - min_num] > 0) { max_count = max(max_count, count(nums, num, k)); } } return num_to_count[k - min_num] + max_count; } private: int count(const vector<int> &nums, const int target, const int k) { const int n = static_cast<int>(nums.size()); int ret = 0; for (int c = 0, i = 0; i < n; ++i) { if (nums[i] == target) { ++c; } else if (nums[i] == k) { --c; } c = max(0, c); ret = max(ret, c); } return ret; } }; ``` **2. Use the `DP`** ``` /** * Time Complexity: O(n * num_range) * Space Complexity: O(num_range) * where `n` is the length of the vector `nums` * `num_range` is (`max_num` - `min_num` + 1) * `max_num` is the maximum number of the vector `nums` * `min_num` is the minimum number of the vector `nums` */ class Solution { public: int maxFrequency(const vector<int> &nums, const int k) { const auto mm = minmax_element(nums.begin(), nums.end()); const int min_num = *mm.first; const int max_num = *mm.second; const int num_range = max_num - min_num + 1; bool exists[num_range]; memset(exists, 0, sizeof(exists)); for (const int num : nums) { exists[num - min_num] = true; } int ret = 0; for (int target = min_num; target < max_num + 1; ++target) { if (!exists[target - min_num]) { continue; } /** * let `n` be the length of the vector `nums`. * change the element whose value is `target` to `k` in a subarray * from nums[i] to nums[j] where 0 <= i <= j <= n - 1. * the whole array `nums` can be divided in three parts, * 1. the left part, that is the subarray from nums[0] to nums[i - 1] * 2. the middle part, that is the subarray from nums[i] to nums[j] * 3. the right part, that is the subarray from nums[j + 1] to nums[n - 1] * * 1. `f0[i]` stands for the maximum frequency of the value `k` after the operation * if `nums[i]` is in the left part * so f0[i] = f0[i - 1] + (nums[i] == k ? 1 : 0) * 2. `f1[i]` stands for the maximum frequency of the value `k` after the operation * if `nums[i]` is in the middle part * so f1[i] = max(f0[i - 1], f1[i - 1]) + (nums[i] == target ? 1 : 0) * 3. `f2[i]` stands for the maximum frequency of the value `k` after the operation * if `nums[i]` is in the right part * so f2[i] = max(f1[i - 1], f2[i - 1]) + (nums[i] == k ? 1 : 0) */ int f0 = 0; int f1 = 0; int f2 = 0; for (const int num : nums) { f2 = max(f1, f2) + (num == k ? 1 : 0); f1 = max(f0, f1) + (num == target ? 1 : 0); f0 += num == k ? 1 : 0; } ret = max({ret, f1, f2}); } return ret; } }; ``` **3. Use the same idea as `2` with the more efficient time complexity** ``` /** * Time Complexity: O(n) * Space Complexity: O(num_range) * where `n` is the length of the vector `nums` * `num_range` is (`max_num` - `min_num` + 1) * `max_num` is the maximum number of the vector `nums` * `min_num` is the minimum number of the vector `nums` */ class Solution { public: int maxFrequency(const vector<int> &nums, const int k) { const auto mm = minmax_element(nums.begin(), nums.end()); const int min_num = *mm.first; const int max_num = *mm.second; const int num_range = max_num - min_num + 1; int f0 = 0; int f1[num_range]; memset(f1, 0, sizeof(f1)); int max_f1 = 0; int f2 = 0; for (const int num : nums) { f2 = max(max_f1, f2) + (num == k ? 1 : 0); f1[num - min_num] = max(f0, f1[num - min_num]) + 1; max_f1 = max(max_f1, f1[num - min_num]); f0 += (num == k ? 1 : 0); } return max(max_f1, f2); } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
C++ solution using Kadane’s Algorithm.
c-solution-using-kadanes-algorithm-by-as-ac5v
IntuitionApproachComplexity Time complexity: Space complexity: Code
ashishlc
NORMAL
2025-01-26T13:30:09.557065+00:00
2025-01-26T13:30:09.557065+00:00
17
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { int findMaxSubArraySumUsingKadane(vector<int>&nums,int x, int k){ int maxSum=-1; int sum=0; //trying to find sub array which have highest frequency of x and then later it can be converted to eleemnt k but if that subarry contain element k, it's value get changed and it won't be the part of max frequency for(int i=0;i<nums.size();i++){ if(nums[i]==k) sum--; if(nums[i]==x) sum++; if(sum<0) sum=0; maxSum = max(sum,maxSum); } return maxSum; } public: int maxFrequency(vector<int>& nums, int k) { unordered_map<int,int>map; for(int i=0;i<nums.size();i++) map[nums[i]]++; int ans=0; for(auto x : map){ int key = x.first; int val = x.second; int maxSum = findMaxSubArraySumUsingKadane(nums,key,k); ans = max(ans,maxSum + map[k]); } return ans; } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
C++ MEMOIZED SOLUTION
c-memoized-solution-by-sj4u-z0x7
IntuitionApproachComplexity Time complexity: Space complexity: Code
SJ4u
NORMAL
2025-01-26T11:34:46.049759+00:00
2025-01-26T11:34:46.049759+00:00
24
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int dp[100001][52][2]; int recurs(vector<int>& nums,int n,int k,int i,int x,bool only_ks_ahead){ //n & k constant i: current idx, x:current subtraction factor if(i>n) return 0; int ans = 0; if(dp[i][x][only_ks_ahead]!=-1) return dp[i][x][only_ks_ahead]; if(nums[i]!=k && !only_ks_ahead){ if(x==51){ // no x chosen till now first elem // choice 1 : make this == k ans = max(ans,recurs(nums,n,k,i+1,nums[i],false)+1); // true denotes sub-array selection has started. // choice 2: don't touch this and start looking from next elem ans = max(ans,recurs(nums,n,k,i+1,x,false)); } else{ // choice 1 : terminate the subarray selection and now only look for values equal to k further ans = max(ans,recurs(nums,n,k,i+1,x,true)+((nums[i]+(k-x)) == k ? 1:0)); //choice 2 : continue subarray with current x ans = max(ans,recurs(nums,n,k,i+1,x,false)+((nums[i]+(k-x)) == k ? 1:0)); } } else if(nums[i]==k){ // choice 1 : if only_ks_ahead than subarray was terminated long back and now count for discrete k's if(only_ks_ahead){ ans = max(ans,recurs(nums,n,k,i+1,x,true)+1); } else{ // choice 2 : here we will continue using current x value and proceed further if(x!=51){ ans = max(ans,recurs(nums,n,k,i+1,x,true)+1); ans = max(ans,recurs(nums,n,k,i+1,x,false)); // or count k and proceed for Only ks from here on } else if(x==51) // Not yet started picking so include k as it is and proceed; ans = max(ans,recurs(nums,n,k,i+1,x,false)+1); } } else{ ans = max(ans,recurs(nums,n,k,i+1,x,true)); // only looking for direct Ks } return dp[i][x][only_ks_ahead]=ans; } int maxFrequency(vector<int>& nums, int k) { int start = 0,ans=0,n = nums.size()-1,end = nums.size()-1; memset(dp,-1,sizeof(dp)); // while(start<=end){ // if(nums[start]!=k) // break; // else // start++; // } // if(start>end) // return start; // while(end>=0){ // if(nums[end]!=k) // break; // else // end--; // } // // so now we have a range to look our answer into, post trimming start and end. // ans = start+(n-end); ans+= recurs(nums,end,k,start,51,false);// 51: denoting starting point for subarray return ans; } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
O(n) Solution, like the Tetris Game
on-solution-like-the-tetris-game-by-lilo-gmvw
Intuition12 Years ago, I came accross an algorithm problem, whose solution was to use the Tetris thinking. This problem is the same.Approach Count the number of
lilongxue
NORMAL
2025-01-26T10:54:47.330716+00:00
2025-01-26T14:00:28.725290+00:00
21
false
# Intuition 12 Years ago, I came accross an algorithm problem, whose solution was to use the Tetris thinking. This problem is the same. # Approach 1. Count the number of ks in nums. It's the initial value of the result. 2. Go thru nums, and for each index, we know how many ks have been encountered (countFL), and how many ks are yet to come (countFR). 3. For each element val, if it !== k, we increment its freq by 1. 4. Otherwise, a k is here. We kill the bottom line: decrement all existing positive freqs by 1. The operation maps the cancel-out effect by a value of k. 5. And the outcome here is countFL + Math.max(...all freqs) + countFR. 6. For each outcome, we do an update: result = Math.max(result, outcome). # Complexity - Time complexity: O(n) - Space complexity: O(n) # Code ```javascript [] /** * @param {number[]} nums * @param {number} k * @return {number} */ var maxFrequency = function(nums, k) { // count k in nums -- the initial value of the result const kCount = nums.reduce((acc, cur) => acc + (cur === k), 0) const ub = 51 // the table records freqs so far, // and it will have the 'kill-line' effect applied const table = new Array(ub).fill(0) let result = kCount // how many ks have been encountered so far let countFL = 0 for (const val of nums) { if (val === k) { countFL++ } // how many ks are not encountered yet const countFR = kCount - countFL if (val !== k) { // for a non-k value, increment its frequency by 1 table[val]++ } else { // this is the key thinking of the solution: // if we encounter a k, we kill the bottom line: // for each existing positive freq, we decrement it by 1 // to reflect the cancel-out effect for (const [j, freq] of table.entries()) { if (freq > 0) table[j] = freq - 1 } } const outcome = countFL + Math.max(...table) + countFR result = Math.max(result, outcome) } return result }; ``` Note that countFL + countFR === kCount. The code can be optimized to be: # Code ```javascript [] /** * @param {number[]} nums * @param {number} k * @return {number} */ var maxFrequency = function(nums, k) { // count k in nums -- the initial value of the result const kCount = nums.reduce((acc, cur) => acc + (cur === k), 0) const ub = 51 // the table records freqs so far, // and it will have the 'kill-line' effect applied const table = new Array(ub).fill(0) let result = kCount for (const val of nums) { if (val !== k) { // for a non-k value, increment its frequency by 1 table[val]++ } else { // this is the key thinking of the solution: // if we encounter a k, we kill the bottom line: // for each existing positive freq, we decrement it by 1 // to reflect the cancel-out effect for (const [j, freq] of table.entries()) { if (freq > 0) table[j] = freq - 1 } } const outcome = kCount + Math.max(...table) result = Math.max(result, outcome) } return result }; ```
0
0
['JavaScript']
0
maximum-frequency-after-subarray-operation
For me it was hard to find .
for-me-it-was-hard-to-find-by-madhavendr-v7wc
IntuitionHere we are checking for all 50 constrain.ApproachNow first make loop for 50 constrain and find the max frequency present in the array and then count p
Madhavendrasinh44
NORMAL
2025-01-26T10:27:00.106101+00:00
2025-01-26T10:27:00.106101+00:00
30
false
# Intuition Here we are checking for all 50 constrain. # Approach Now first make loop for 50 constrain and find the max frequency present in the array and then count plus the frequency found. # Complexity - Time complexity: $$O(50+nums.size())$$ - Space complexity: $$O(50 + n)$$ # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int cnt = 0; for (int i = 0; i < nums.size(); i++) { if (nums[i] == k) cnt++; } int res = cnt; for (int i = 1; i <= 50; i++) { if (i == k) { continue; } int currsum = 0; int maxsum = 0; for (int j = 0; j < nums.size(); j++) { int val = 0; if (nums[j] == i) { val = 1; } else if (nums[j] == k) { val = -1; } currsum = max(val, currsum + val); maxsum = max(maxsum, currsum); } res = max(res, cnt + maxsum); } return res; } }; ```
0
0
['C++']
1
maximum-frequency-after-subarray-operation
For me it was hard to find .
for-me-it-was-hard-to-find-by-madhavendr-fc83
IntuitionHere we are checking for all 50 constrain.ApproachNow first make loop for 50 constrain and find the max frequency present in the array and then count p
Madhavendrasinh44
NORMAL
2025-01-26T10:26:56.684270+00:00
2025-01-26T10:26:56.684270+00:00
11
false
# Intuition Here we are checking for all 50 constrain. # Approach Now first make loop for 50 constrain and find the max frequency present in the array and then count plus the frequency found. # Complexity - Time complexity: $$O(50+nums.size())$$ - Space complexity: $$O(50 + n)$$ # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int cnt = 0; for (int i = 0; i < nums.size(); i++) { if (nums[i] == k) cnt++; } int res = cnt; for (int i = 1; i <= 50; i++) { if (i == k) { continue; } int currsum = 0; int maxsum = 0; for (int j = 0; j < nums.size(); j++) { int val = 0; if (nums[j] == i) { val = 1; } else if (nums[j] == k) { val = -1; } currsum = max(val, currsum + val); maxsum = max(maxsum, currsum); } res = max(res, cnt + maxsum); } return res; } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
easy solution in O(n) just store diff and find max subarray sum
easy-solution-in-on-just-store-diff-and-sbncf
Intuitionsince the range of nums[i] is very less the diff between the nums[i] and k can be as large as -50 to 50 only so we can just check for each possible val
Unos555
NORMAL
2025-01-26T09:56:26.543936+00:00
2025-01-26T09:56:26.543936+00:00
18
false
# Intuition since the range of nums[i] is very less the diff between the nums[i] and k can be as large as -50 to 50 only so we can just check for each possible value and find the one with max freq # Approach -> store the diff of all elements from k which will be req number to add to make curr nums[i] to k -> now for each value in set check the maximum freq of k we can achieve by adding curr value -> to check maximum achievable freq we can just reconstruct the array as if already k then make it -k as we will be losing this one and if after adding curr value we get k then it should be k(i.e we get a k) otherwise leave the 0 now we can find the max subarray sum and return sum/k+already present k's and hence solved. # Complexity - Time complexity: O(n) - Space complexity: O(n) # Code ```cpp [] class Solution { public: int calc(int diff,vector<int>& nums,int k){ vector<int> arr(nums.size(),0); int ct=0; for (int i=0;i<nums.size();i++){ if (nums[i]==k){ ct++; arr[i]=-k; }else{ if (nums[i]-diff==k){ arr[i]=k; } } } int maxx=0; int curr=0; for (int i=0;i<nums.size();i++){ curr=max(curr+arr[i],arr[i]); maxx=max(curr,maxx); } return maxx/k+ct; } int maxFrequency(vector<int>& nums, int k) { ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); int n=nums.size(); set<int> diff; int maxi=0; for (int i=0;i<n;i++){ if ((nums[i]-k)!=0){ diff.insert(nums[i]-k); } if (nums[i]==k){ maxi++; } } for (auto val:diff){ maxi=max(calc(val,nums,k),maxi); } return maxi; } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
Normal Solution
normal-solution-by-maheshsyamk-g564
IntuitionApproachComplexity Time complexity: Space complexity: Code
MaheshSyamK
NORMAL
2025-01-26T09:46:47.540149+00:00
2025-01-26T09:46:47.540149+00:00
17
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int n = nums.size(), res = 0, pre = 0; vector<int> suf(n+1), dp(51); for(int i = n - 1; i >= 0; i--) suf[i] = suf[i+1] + (nums[i] == k); for(int i = 0; i < nums.size(); i++) { dp[nums[i]] = max(dp[nums[i]] + 1, pre + 1); res = max(res, dp[nums[i]] + suf[i+1]); pre += (nums[i] == k); } return res; } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
C++ Solution :- Kadane Algorithm
c-solution-kadane-algorithm-by-shogun_th-z2cx
Approach First, compute the initial count of elements equal to k in the array. This serves as the baseline count before any operations. Identify all possible
Shogun_the_Great
NORMAL
2025-01-26T09:21:15.581202+00:00
2025-01-26T09:21:15.581202+00:00
15
false
# Approach <!-- Describe your approach to solving the problem. --> - First, compute the initial count of elements equal to k in the array. This serves as the baseline count before any operations. - Identify all possible values of x that can be added to a subarray to convert some elements to k. - These values are derived from the elements of the array as x = k - num for each element num in nums, excluding x = 0 since it does not change the array. - For each possible value of x, transform the array into a gain/loss array where :- - +1 is assigned to elements that can be converted to k by adding x. - -1 is assigned to elements that are already k (since including them in the subarray might reduce the gain). 0 is assigned to other elements. - Track the maximum gain across all possible values of x and add it to the original count of k to get the final result. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int original_count = 0; // Calculate the original frequency of k for (int num : nums) { if (num == k) original_count++; } unordered_set<int> x_set; // Collect all possible x values (k - num) where x != 0 for (int num : nums) { int x = k - num; if (x != 0) { x_set.insert(x); } } int max_gain = 0; // Track the maximum gain from any subarray operation // For each possible x, compute the maximum subarray gain using Kadane's algorithm for (int x : x_set) { int current_sum = 0; int max_subarray = 0; for (int num : nums) { int val = 0; if (num == k) { // Including this element in the subarray with x != 0 will turn it into k + x (not k), leading to a loss val = -1; } else if (num == (k - x)) { // This element can be converted to k by adding x, leading to a gain val = 1; } else { // This element is unaffected by adding x, no gain or loss val = 0; } // Kadane's algorithm: decide whether to start a new subarray or extend the current one current_sum = max(val, current_sum + val); // Update the maximum subarray sum found max_subarray = max(max_subarray, current_sum); } // Update the overall maximum gain across all x values if (max_subarray > max_gain) { max_gain = max_subarray; } } // The final answer is the original count plus the best gain from one operation return original_count + max_gain; } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
Array | C++ | O(N)
array-c-on-by-a_ck-l3ma
IntuitionThe problem revolves around identifying the maximum frequency of a number in the array while applying certain modifications. My initial thought was to
a_ck
NORMAL
2025-01-26T09:17:22.008523+00:00
2025-01-26T09:17:22.008523+00:00
18
false
# Intuition The problem revolves around identifying the maximum frequency of a number in the array while applying certain modifications. My initial thought was to leverage a frequency array approach to keep track of counts efficiently. By iterating through the array and managing counts dynamically, the solution could be computed in a structured way. # Approach The approach involves: 1. Iterating through the array to calculate the initial frequency of the target number `k`. 2. Using a frequency array to maintain counts for all potential values in the range. 3. For each number, checking how many elements I can change if I want to make each number to `k`. If the current number is `k`, then we can reduce the count for each number(except for `k`). 4. Updating the result based on the maximum achievable frequency at every step. # Complexity - Time complexity: The algorithm iterates over the array multiple times and utilizes a nested loop to update frequencies for numbers in a fixed range (1 to 50). Thus, the time complexity is $$O(n \cdot 50)$$, which simplifies to $$O(n)$$. - Space complexity: A frequency array of fixed size (51) is used, making the space complexity $$O(1)$$. # Code ```cpp class Solution { public: int maxFrequency(vector<int>& nums, int k) { int tot = 0; const int n = (int)nums.size(); for (int i = 0; i < n; ++i) { if (nums[i] == k) tot++; } int ans = 0; vector<int> cnt(51, 0); for (int i = 0; i < n; ++i) { for (int j = 1; j <= 50; ++j) { if (nums[i] == j) cnt[j]++; if (nums[i] == k && cnt[j] > 0) cnt[j]--; ans = max(ans, tot + cnt[j]); } } return ans; } };
0
0
['C++']
0
maximum-frequency-after-subarray-operation
Prefix sum | Simple solution with 100% beaten
prefix-sum-simple-solution-with-100-beat-nvzf
IntuitionThe goal of the problem is to find the maximum frequency of a given integer k in the array nums after performing a single operation. In this operation,
Takaaki_Morofushi
NORMAL
2025-01-26T09:07:58.574740+00:00
2025-01-26T09:07:58.574740+00:00
14
false
# Intuition The goal of the problem is to find the maximum frequency of a given integer `k` in the array `nums` after performing a single operation. In this operation, we can select a subarray and add an integer `x` to all the elements in that subarray. The challenge is to maximize the frequency of `k` through this operation. # Approach We can approach this problem by iterating through the `nums` array while maintaining the frequency of each number and the frequency of `k`. For each number, we update the frequency array while ensuring that if a number is equal to `k`, we increment a separate counter to keep track of how often `k` appears. The key observation is that by adding `x` to a subarray, we may increase the occurrences of `k` and thus maximize its frequency. ### Steps: 1. Initialize a frequency array `cnt` to store the frequency of numbers in `nums`. 2. Initialize a counter `cnt_k` to count the occurrences of `k` in `nums`. 3. Iterate through the array, updating the frequency of the current number and checking if it is equal to `k`. If it is, increment the `cnt_k`. 4. Track the maximum frequency of any number at each step using a variable `res`. # Complexity - **Time complexity**: \(O(n)\), where \(n\) is the length of the array `nums`, since we only iterate through the array once. - **Space complexity**: \(O(1)\), as we are using a fixed-size array `cnt` of size 51 to track frequencies. # Code ```cpp class Solution { public: int maxFrequency(vector<int>& nums, int k) { vector<int> cnt(51, 0); // Frequency array for values in the range [0, 50] int maxFrequency = 0; int countK = 0; for (int num : nums) { cnt[num] = max(cnt[num], countK) + 1; // Update frequency of the current number if (num == k) { countK++; // Track the frequency of `k` } maxFrequency = max(maxFrequency, cnt[num]); // Update the maximum frequency } return maxFrequency; } };
0
0
['C++']
0
maximum-frequency-after-subarray-operation
Kadane Go Solution !!!
kadane-go-solution-by-dipak__patil-0drb
Code
dipak__patil
NORMAL
2025-01-26T08:52:10.269059+00:00
2025-01-26T08:52:10.269059+00:00
10
false
# Code ```golang [] func maxFrequency(nums []int, k int) (res int) { var ( countMap = map[int]int{} n int ) for _, n = range nums { countMap[n]++ } kadane := func(num int) int { var currRes, currCount int for _, n = range nums { if n == k { currCount-- } if n == num { currCount++ } if currCount < 0 { currCount = 0 } currRes = max(currRes, currCount) } return currRes } for key, _ := range countMap { res = max(res, kadane(key)) } return res + countMap[k] } ```
0
0
['Go']
0
maximum-frequency-after-subarray-operation
check each x, maximum subarray sum
check-each-x-by-user5285zn-h3cd
We fix x and find the interval in which we convert all x to k. b contains the difference between the frequencies between x and k in the prefix.
user5285Zn
NORMAL
2025-01-26T08:40:25.356857+00:00
2025-01-26T08:43:53.834945+00:00
7
false
We fix $x$ and find the interval in which we convert all $x$ to $k$. $b$ contains the difference between the frequencies between $x$ and $k$ in the prefix. ```rust [] fn f(x:i32, nums: &[i32], k: i32) -> i32 { let mut a = 0; let mut b = 0; let mut best = 0; for &y in nums.iter() { if y == x {b += 1} if y == k {b -= 1} best = best.max(b-a); a = a.min(b) } best } impl Solution { pub fn max_frequency(nums: Vec<i32>, k: i32) -> i32 { let s = nums.iter().filter(|&&x|x==k).count() as i32; s + (1..=51).map(|x|f(x,&nums,k)).max().unwrap() } } ```
0
0
['Rust']
0
maximum-frequency-after-subarray-operation
Subtract all possibilities: O(n*50)
subtract-all-possibilities-on50-by-tejes-c33d
Complexity Time complexity: O(n) Space complexity: O(n) Code
tejesh_avadanam
NORMAL
2025-01-26T08:21:13.508089+00:00
2025-01-26T08:21:13.508089+00:00
15
false
# Complexity - Time complexity: O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int n = nums.size(); int maxFrequency = 0; vector<int> kIndices; int frequency = 0; for (int i = 0; i < n; ++i) { if (nums[i] == k) { kIndices.push_back(i); frequency++; } } if(frequency == n) return n; int m = kIndices.size(); for (int x = -50; x <= 50; ++x) { int sumFrequency = 0; int bias = 0; for (int idx = 0; idx <= m; ++idx) { int start = (idx == 0) ? 0 : kIndices[idx - 1] + 1; int end = (idx == m) ? n - 1 : kIndices[idx] - 1; int currentFrequency = 0; for (int j = start; j <= end; ++j) { if (nums[j] + x == k) { ++currentFrequency; } } if(sumFrequency + currentFrequency >= bias + 1){ sumFrequency += currentFrequency; maxFrequency = max({maxFrequency, currentFrequency + frequency, sumFrequency - bias + frequency}); bias++; } else { bias = 0; sumFrequency = 0; } } } return maxFrequency; } }; ```
0
0
['C++']
0
maximum-frequency-after-subarray-operation
C++ solution using prefix sum and map with intuition and approach
c-solution-using-prefix-sum-and-map-with-zr2j
Intuitionfor each index if we considering subarry ending index as curr index we need to find a index from 0 to i for which our ans will be max.for this we can c
jatinaggarwal2812
NORMAL
2025-01-26T07:49:57.934144+00:00
2025-01-26T07:49:57.934144+00:00
61
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> for each index if we considering subarry ending index as curr index we need to find a index from 0 to i for which our ans will be max. for this we can convert every nums[i] to k from 0 to i, so we can convert from last index where nums[i] is occuring because if we convert previous to them also elements which are already k will be also changed. # Approach <!-- Describe your approach to solving the problem. --> Prefix sum is 2d vector of size n+1 which is storing count of all elements for every index. Unordered map is used to store where the element last is present. For current index we to have to find i we have to find all k from i+1 to n, we can convert all numbers till last index where nums[i] occurred but we not need to convert total k from last index to i if count of k from last idx to i is greater than that count of number to be converted from idx to i and update last index to i our ans will k count from 0 to lastindex-1 + curr element count from last index to curr index + k count from curr index +1 to n # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> o(50*n) # Code ```cpp [] class Solution { public: int maxFrequency(vector<int>& nums, int k) { int n = nums.size(); vector<vector<int>> pre; vector<int> curr(51,0); pre.push_back(curr); for(auto it:nums){ curr[it]++; pre.push_back(curr); } // for(auto it:pre){ // for(auto itr:it){ // cout<<itr<<" "; // } // cout<<endl; // } unordered_map<int,int> mp; int ans=0; for(int i=0;i<n;i++){ int temp = pre[n][k]-pre[i+1][k]; int ones = pre[i+1][k]-pre[0][k]; ans=max(ans,temp+ones); auto it = mp.find(nums[i]); if(it==mp.end()){ mp[nums[i]]=i; ans=max(ans,1+temp+pre[i][k]-pre[0][k]); } else { int temp1 = pre[i+1][nums[i]]-pre[mp[nums[i]]][nums[i]]; int temp2 = pre[i+1][k]-pre[mp[nums[i]]][k]; int temp3 = pre[mp[nums[i]]+1][k]-pre[0][k]; if(temp1<=temp2){ mp[nums[i]]=i; // ans=max(ans, temp+ones); } else{ ans=max(ans,temp+temp1+temp3); } } } return ans; } }; ```
0
0
['Prefix Sum', 'C++']
0
minimum-edge-weight-equilibrium-queries-in-a-tree
【C++ | Java | Python】Prefix-sum and LCA on the tree, explained in detail
c-java-python-prefix-sum-and-lca-on-the-7nlor
I know almost nothing about English, pointing out the mistakes in my article would be much appreciated.\n\n> In addition, I\'m too weak, please be critical of m
RealFan
NORMAL
2023-09-03T07:57:47.144620+00:00
2023-09-14T08:52:47.923771+00:00
3,602
false
> **I know almost nothing about English, pointing out the mistakes in my article would be much appreciated.**\n\n> **In addition, I\'m too weak, please be critical of my ideas.**\n---\n\n[toc]\n\n# Intuition\n1. For this kind of problem involves the "path between two nodes on the tree", **the first intuition is to consider their [lowest common ancestor](https://en.wikipedia.org/wiki/Lowest_common_ancestor)(LCA)**.\n Suppose we have known the LCA of every nodes pair. How to use it?\n2. If we know the LCA of $$x$$ and $$y$$ is $$L$$, the path of $$x \\leftrightarrow y $$ can be divided into two segments: $$x \\leftrightarrow L$$ and $$y \\leftrightarrow L$$.\n So we can research them separately.\n3. The problem requires the edge weights to be equal with minimum changes. **So we should retain a most occurrences weight $$z$$, and change the others.**\n4. Notice that the range of edge weights is very small (26 in this problem), so immediately consider **enumerating all possible weights as retained weight $$z$$**.\n\n5. Now, we have 2 problems: \n 1. **How to count the number of edges on the path of $$x \\leftrightarrow L$$?**\n 2. **How to count the number of $$z$$ occurs on the path of $$x \\leftrightarrow L$$?** \n (The $$y \\leftrightarrow L$$ can solved in the same way).\n\n6. For the first problem:\n Because the $$L$$ is an ancestor of $$x$$, the edges must equals to the difference of their depth:\n $$edges = d[x] - d[L]$$\n7. For the second problem: \n This is an interval summation problem, which can be solved by following the idea of prefix-sum.\n For each node $$x$$, we can maintain an array `w[x]`. **`w[x][i]` saves the prefix-count of weight $$i$$ until $$x$$.** *(More formally, `w[x][i]` saves "from $$root$$ to $$x$$, the number of edges which has weight $$i$$".)*\n As a result, the $$i$$\'s count in $$ x \\leftrightarrow L $$ can be calculated easily:\n $$cnt(i) = w[x][i] - w[L][i]$$\n\n *Can read #example at the end of this article to enhance understanding*\n\n8. And finally, how to calculate the LCA?\n There are many methods to find the LCA of nodes on a tree. The easiest way is to use [binary lifting](https://codeforces.com/blog/entry/100826). As I mentioned [last week](https://leetcode.com/problems/maximize-value-of-function-in-a-ball-passing-game/solutions/3965411/c-java-python-binary-lifting/) as well.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. For convenience, in addition to the 2D array `fa` required by binary lifting, we also maintain an array `d` as the depth of each node. \n The depth of root node is $$0$$, and the child node\'s depth is one more than its father. Easily use [dfs](https://en.wikipedia.org/wiki/Depth-first_search) to get these information. \n2. In `lca(x, y)` function, we first adjust the $$x$$ and $$y$$ to the same level, because the LCA will never be deeper than $$x$$ or $$y$$.\n **After the adjustment, the distant of $$x$$ to $$L$$ and $$y$$ to $$L$$ will be equal.** It\'s actually same with [Two Linked Lists Intersection](https://leetcode.com/problems/intersection-of-two-linked-lists/) problem.\n\n **So, we jump $$x$$ and $$y$$ upward together, they will first meet on their LCA.** \n\n - If $$x = y$$, can directly return $$x$$ as the result. \n - Otherwise, we want to **find the $$u,v$$ as the ancestor nodes of $$x,y$$ which are one level below their LCA**. Try going from long-step to short-step:\n - If jump $$2^p$$ steps makes $$x$$ and $$y$$ together, it means $$2^p$$ is too long.\n - If $$2^{p}$$ can\'t make them together, it means we can jump $$2^p$$ safely. \n At the same time, the rest bits only allow jumping $$2^{p-1}+...+1 =2^p-1$$ steps at most. So if we don\'t jump this time, we will miss the $$u,v$$ forever.\n\n As a result, we choose to jump $$2^p$$ if it can\'t make $$x,y$$ equal.\n Finally, we can return the father of $$x$$ or $$y$$ as the LCA.\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n \\log n + q(C + \\log n))$$\n- Space complexity: $$ O(n \\log n) $$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` C++ []\nclass Solution {\npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n int m = (int)log2(n) + 1, C = 27;\n vector<vector<pair<int, int>>> g(n);\n for (auto& e : edges) {\n g[e[0]].push_back(make_pair(e[1], e[2]));\n g[e[1]].push_back(make_pair(e[0], e[2]));\n }\n\n // fa[i][j] means the 2^i -th father of vertex j:\n vector<vector<int>> fa(m, vector<int>(n));\n // w[i][j] means the count of j from root to vertex i:\n vector<vector<int>> w(n);\n // d[i] means the depth of vertex i:\n vector<int> d(n, 0);\n\n function<void(int, int, int)> dfs = [&](int x, int f, int dep) -> void {\n fa[0][x] = f;\n d[x] = dep;\n for (auto& [c, weight] : g[x]) {\n if (f == c) continue;\n w[c] = w[x];\n w[c][weight]++;\n dfs(c, x, dep + 1);\n }\n };\n w[0] = vector<int>(C, 0);\n dfs(0, 0, 0);\n // binary lifting: \n for (int i = 1; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n fa[i][j] = fa[i-1][fa[i-1][j]];\n }\n }\n\n auto lca = [&](int x, int y) -> int {\n if (d[x] > d[y]) swap<int>(x, y);\n // adjust x and y to the same depth:\n for (int p = 0; (1 << p) <= d[y] - d[x]; ++p) \n if ((1 << p) & d[y] - d[x]) y = fa[p][y];\n // conservatively jump x and y together:\n for (int p = m - 1; p >= 0; --p) {\n if (fa[p][x] != fa[p][y]) {\n x = fa[p][x];\n y = fa[p][y];\n }\n }\n return x == y ? x : fa[0][x];\n };\n \n vector<int> res;\n for (auto &q: queries) {\n int x = q[0], y = q[1], l = lca(x, y);\n // the total length between x and y:\n int len = d[x] + d[y] - 2 * d[l];\n // the mode of weight between x and y:\n int max_z = 0;\n for (int z = 1; z < C; ++z) {\n int num_z = w[x][z] + w[y][z] - w[l][z] * 2;\n max_z = max(max_z, num_z);\n }\n // the others must be changed:\n res.push_back(len - max_z);\n }\n return res;\n }\n};\n```\n``` Java []\nclass Solution {\n public void dfs(int x, int f, int dep, List<Pair<Integer, Integer>> []g, int [][]fa, int [][]w, int []d) {\n fa[0][x] = f;\n d[x] = dep;\n for (Pair<Integer, Integer> p: g[x]) {\n //Pair<Integer, Integer> p = g[x].get(i);\n int c = p.getKey().intValue(), weight = p.getValue().intValue();\n if (f == c) continue;\n for (int j = 0; j < w[c].length; ++j)\n w[c][j] = w[x][j];\n w[c][weight]++;\n dfs(c, x, dep + 1, g, fa, w, d);\n }\n }\n public int lca(int x, int y, int [][]fa, int []d) {\n int m = fa.length;\n if (d[x] > d[y]) {\n int t = x;\n x = y;\n y = t;\n }\n // adjust x and y to the same depth:\n for (int p = 0; (1 << p) <= d[y] - d[x]; ++p) {\n if (((1 << p) & d[y] - d[x]) != 0) {\n y = fa[p][y];\n }\n }\n // conservatively jump x and y together:\n for (int p = m - 1; p >= 0; --p) {\n if (fa[p][x] != fa[p][y]) {\n x = fa[p][x];\n y = fa[p][y];\n }\n }\n return x == y ? x : fa[0][x];\n }\n public int[] minOperationsQueries(int n, int[][] edges, int[][] queries) {\n int m = 15, C = 27;\n List<Pair<Integer, Integer>> []g = new ArrayList[n];\n for (int i = 0; i < n; ++i)\n g[i] = new ArrayList<Pair<Integer, Integer>>();\n for (int[] e : edges) {\n g[e[0]].add(new Pair<Integer, Integer>(e[1], e[2]));\n g[e[1]].add(new Pair<Integer, Integer>(e[0], e[2]));\n }\n\n // fa[i][j] means the 2^i -th father of vertex j:\n int [][]fa = new int[m][n];\n // w[i][j] means the count of j from root to vertex i:\n int [][]w = new int[n][C];\n // d[i] means the depth of vertex i:\n int []d = new int[n];\n dfs(0, 0, 0, g, fa, w, d);\n // binary lifting: \n for (int i = 1; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n fa[i][j] = fa[i-1][fa[i-1][j]];\n }\n }\n \n int []res = new int[queries.length];\n for (int i = 0; i < queries.length; ++i) {\n int x = queries[i][0], y = queries[i][1], l = lca(x, y, fa, d);\n // the total length between x and y:\n int len = d[x] + d[y] - 2 * d[l];\n // the mode of weight between x and y:\n int max_z = 0;\n for (int z = 1; z < C; ++z) {\n int num_z = w[x][z] + w[y][z] - w[l][z] * 2;\n max_z = Math.max(max_z, num_z);\n }\n // the others must be changed:\n res[i] = len - max_z;\n }\n return res;\n }\n}\n```\n``` Python3 []\nclass Solution:\n def minOperationsQueries(self, n, edges, queries):\n m, C = n.bit_length() + 1, 27\n g = [[] for i in range(n)]\n for e in edges:\n g[e[0]].append((e[1], e[2]))\n g[e[1]].append((e[0], e[2]))\n\n # fa[i][j] means the 2^i -th father of vertex j:\n fa = [[0 for i in range(n)] for j in range(m)]\n # w[i][j] means the count of j from root to vertex i:\n w = [None for i in range(n)] \n # d[i] means the depth of vertex i:\n d = [0] * n\n\n def dfs(x, f, dep):\n fa[0][x] = f \n d[x] = dep \n for (c, weight) in g[x]:\n if f == c: continue\n w[c] = w[x].copy()\n w[c][weight] += 1\n dfs(c, x, dep + 1)\n w[0] = [0] * C\n dfs(0, 0, 0)\n\n for i in range(1, m):\n for j in range(n):\n fa[i][j] = fa[i-1][fa[i-1][j]]\n\n def lca(x, y):\n if d[x] > d[y]: x, y = y, x\n # adjust x and y to the same depth:\n for p in range(m):\n if (1 << p) & (d[y] - d[x]): \n y = fa[p][y]\n # conservatively jump x and y together:\n for p in range(m-1, -1, -1):\n if fa[p][x] != fa[p][y]:\n x = fa[p][x]\n y = fa[p][y]\n return x if x == y else fa[0][x]\n\n res = []\n for q in queries:\n x, y, l = q[0], q[1], lca(q[0], q[1])\n # the total length between x and y:\n length = d[x] + d[y] - 2 * d[l]\n # the mode of weight between x and y:\n max_z = max([w[x][z] + w[y][z] - w[l][z] * 2 for z in range(1, C)])\n # the others must be changed:\n res.append(length - max_z)\n return res\n```\n\n# Example \nThis is a tree:\n![tree.jpg](https://assets.leetcode.com/users/images/85dcd4af-39b9-4338-a485-728f566e1d7c_1693734011.9845061.jpeg)\n\nNow we want to calculate the condition $$\\{z=6, x=4, y=7\\}$$, that is, for node pair $$(4,7)$$, how many edges must be changed to let all edges be $$6$$?\n\n![path.jpg](https://assets.leetcode.com/users/images/d602c639-e05a-4a4b-8ac7-041e7ba4cf0d_1693734032.6217048.jpeg)\nWe find $$LCA(4,7)=1$$, and:\n- the number of weight $$6$$ in $$4 \\leftrightarrow 1$$ is: $$w[4][6] - w[1][6] = 2$$\n- the number of weight $$6$$ in $$7 \\leftrightarrow 1$$ is: $$w[7][6] - w[1][6] = 1$$.\n\nSo the total $$6$$ in $$4 \\leftrightarrow 1 \\leftrightarrow 7$$ is $$2+1=3$$.\nWhile the number of edge is $$(d[4] - d[1]) + (d[7] - d[1]) = 5$$.\n\nAs a result, $$5-3=2$$ edges must be changed to $$6$$ in this condition.\n\n
81
1
['Depth-First Search', 'C++', 'Java', 'Python3']
13
minimum-edge-weight-equilibrium-queries-in-a-tree
LCA in C++, java and python
lca-in-c-java-and-python-by-cpcs-0ira
Intuition\nUse LCA.\n\n# Approach\nThere are at most 26 different edge weights. For each node, we can count the number of edges of each weight from root to the
cpcs
NORMAL
2023-09-03T04:00:48.967731+00:00
2023-09-03T12:12:03.664377+00:00
2,198
false
# Intuition\nUse LCA.\n\n# Approach\nThere are at most 26 different edge weights. For each node, we can count the number of edges of each weight from root to the current node.\nAnd then for each query (x, y),\nThe number of edges of a particular weight = num[x] + num[y] - 2 * num[LCA(x, y)].\nThen we just calculate the median of the weights. So we need a fast algorithm to claculate LCA. We can just save the 2 ^ n parent of each node...\n\n# Complexity\n- Time complexity:\nO(log(n) * q * 26) where q is the number of queries and n is the number of nodes.\n\n- Space complexity:\nO(n * log(n))\n\n# Code\nC++\n```\nclass Solution {\n void dfs(const vector<vector<pair<int, int>>> &con, int x, int p, vector<int> &b, vector<int> &e, vector<vector<int>> &f, int &t, vector<vector<int>> &all, vector<int> &w) {\n all[x] = w;\n f[x][0] = p;\n b[x] = ++t;\n for (const auto& v : con[x]) {\n if (v.first != p) {\n ++w[v.second];\n dfs(con, v.first, x, b, e, f, t, all, w);\n --w[v.second];\n }\n }\n e[x] = t;\n}\n \n// Is x an ancestor of y?\nbool isAncestor(const vector<int> &b, const vector<int> &e, int x, int y) {\n\treturn b[x] <= b[y] && e[x] >= e[y];\n}\n \nint lca(const vector<vector<int>> &f, const vector<int> &b, const vector<int> &e, int x, int y) {\n\tif (isAncestor(b, e, x, y)) {\n\t\treturn x;\n\t}\n\tif (isAncestor(b, e, y, x)) {\n\t\treturn y;\n\t}\n \n\tint r = 0;\n\tfor (int i = 19; i >= 0; --i) {\n\t\tconst int temp = f[x][i];\n\t\tif (isAncestor(b, e, temp, y)) {\n\t\t\tr = temp;\n\t\t} else {\n\t\t\tx = temp;\n\t\t}\n\t}\n\treturn r;\n}\n\npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n vector<vector<pair<int, int>>> con(n);\n for (const auto& e : edges) {\n con[e[0]].push_back({e[1], e[2] - 1});\n con[e[1]].push_back({e[0], e[2] - 1});\n }\n vector<vector<int>> all(n), f(n, vector<int>(20));\n\t vector<int> b(n), e(n), w(26);\n\t int t = 0;\n\t dfs(con, 0, -1, b, e, f, t, all, w);\n\t f[0][0] = 0;\n\t for (int i = 1; i < 20; ++i) {\n\t\t for (int j = 0; j < n; ++j) {\n\t\t\t f[j][i] = f[f[j][i - 1]][i - 1];\n\t\t }\n\t }\n vector<int> r;\n for (const auto& q : queries) {\n if (q[0] == q[1]) {\n r.push_back(0);\n continue;\n }\n const int t = lca(f, b, e, q[0], q[1]);\n int sum = 0, m = 0;\n for (int i = 0; i < 26; ++i) {\n const int temp = all[q[0]][i] + all[q[1]][i] - (all[t][i] << 1);\n sum += temp;\n m = max(m, temp);\n }\n r.push_back(sum - m);\n }\n return r;\n }\n};\n\n```\n\nJava\n```\nclass Solution {\n public int[] minOperationsQueries(int n, int[][] edges, int[][] queries) {\n List<Pair>[] con = new ArrayList[n];\n for (int i = 0; i < n; i++) {\n con[i] = new ArrayList<>();\n }\n\n for (int[] e : edges) {\n con[e[0]].add(new Pair(e[1], e[2] - 1));\n con[e[1]].add(new Pair(e[0], e[2] - 1));\n }\n\n int[][] all = new int[n][26];\n int[][] f = new int[n][20];\n int[] b = new int[n];\n int[] e = new int[n];\n int[] w = new int[26];\n\n int[] t = {0};\n dfs(con, 0, -1, b, e, f, t, all, w);\n f[0][0] = 0;\n\n for (int i = 1; i < 20; ++i) {\n for (int j = 0; j < n; ++j) {\n f[j][i] = f[f[j][i - 1]][i - 1];\n }\n }\n\n int[] result = new int[queries.length];\n int index = 0;\n for (int[] q : queries) {\n if (q[0] == q[1]) {\n result[index++] = 0;\n continue;\n }\n int tLca = lca(f, b, e, q[0], q[1]);\n int sum = 0, m = 0;\n for (int i = 0; i < 26; ++i) {\n int temp = all[q[0]][i] + all[q[1]][i] - (all[tLca][i] << 1);\n sum += temp;\n m = Math.max(m, temp);\n }\n result[index++] = sum - m;\n }\n return result;\n }\n\n private static class Pair {\n int first;\n int second;\n\n Pair(int first, int second) {\n this.first = first;\n this.second = second;\n }\n }\n\n void dfs(List<Pair>[] con, int x, int p, int[] b, int[] e, int[][] f, int[] t, int[][] all, int[] w) {\n all[x] = w.clone();\n f[x][0] = p;\n b[x] = ++t[0];\n for (Pair v : con[x]) {\n if (v.first != p) {\n w[v.second]++;\n dfs(con, v.first, x, b, e, f, t, all, w);\n w[v.second]--;\n }\n }\n e[x] = t[0];\n }\n\n boolean isAncestor(int[] b, int[] e, int x, int y) {\n return b[x] <= b[y] && e[x] >= e[y];\n }\n\n int lca(int[][] f, int[] b, int[] e, int x, int y) {\n if (isAncestor(b, e, x, y)) {\n return x;\n }\n if (isAncestor(b, e, y, x)) {\n return y;\n }\n\n int r = 0;\n for (int i = 19; i >= 0; --i) {\n int temp = f[x][i];\n if (isAncestor(b, e, temp, y)) {\n r = temp;\n } else {\n x = temp;\n }\n }\n return r;\n }\n}\n```\nPython\n```\nfrom typing import List\n\nclass Solution:\n def minOperationsQueries(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]:\n def dfs(x, p, b, e, f, t, all, w):\n all[x] = w[:]\n f[x][0] = p\n b[x] = t[0] = t[0] + 1\n for v in con[x]:\n if v[0] != p:\n w[v[1]] += 1\n dfs(v[0], x, b, e, f, t, all, w)\n w[v[1]] -= 1\n e[x] = t[0]\n\n def isAncestor(b, e, x, y):\n return b[x] <= b[y] and e[x] >= e[y]\n\n def lca(f, b, e, x, y):\n if isAncestor(b, e, x, y):\n return x\n if isAncestor(b, e, y, x):\n return y\n r = 0\n for i in range(19, -1, -1):\n temp = f[x][i]\n if isAncestor(b, e, temp, y):\n r = temp\n else:\n x = temp\n return r\n\n con = [[] for _ in range(n)]\n for e in edges:\n con[e[0]].append((e[1], e[2] - 1))\n con[e[1]].append((e[0], e[2] - 1))\n\n all = [[0] * 26 for _ in range(n)]\n f = [[0] * 20 for _ in range(n)]\n b = [0] * n\n e = [0] * n\n w = [0] * 26\n\n t = [0]\n dfs(0, -1, b, e, f, t, all, w)\n f[0][0] = 0\n\n for i in range(1, 20):\n for j in range(n):\n f[j][i] = f[f[j][i - 1]][i - 1]\n\n result = []\n for q in queries:\n if q[0] == q[1]:\n result.append(0)\n continue\n tLca = lca(f, b, e, q[0], q[1])\n _sum, m = 0, 0\n for i in range(26):\n temp = all[q[0]][i] + all[q[1]][i] - (all[tLca][i] << 1)\n _sum += temp\n m = max(m, temp)\n result.append(_sum - m)\n return result\n\n```
20
1
['Python', 'C++', 'Java', 'Python3']
6
minimum-edge-weight-equilibrium-queries-in-a-tree
Video Explanation (Optimizing starting from Brute force)
video-explanation-optimizing-starting-fr-b86d
Explanation\n\nClick here for the video\n\n# Code\n\n#define pii pair<int, int>\n#define F first\n#define S second\n\nconst int N = 1e4+1;\nconst int W = 27;\n\
codingmohan
NORMAL
2023-09-03T06:36:42.765442+00:00
2023-09-03T06:36:42.765493+00:00
539
false
# Explanation\n\n[Click here for the video](https://youtu.be/MJRMqbSJW24)\n\n# Code\n```\n#define pii pair<int, int>\n#define F first\n#define S second\n\nconst int N = 1e4+1;\nconst int W = 27;\n\nvector<vector<int>> par(15, vector<int>(N, 0));\nvector<vector<int>> frq(N, vector<int>(W, 0));\nvector<int> lvl(N, 0);\nvector<vector<pii>> g(N);\n\nclass Solution { \n void Reset() {\n for (auto &i: lvl) i = 0;\n for (auto &i: par) \n for (auto &j: i) j = 0;\n for (auto &i: g)\n i.clear();\n }\n \n void Dfs (int src, int parent) {\n lvl[src] = lvl[parent] + 1;\n \n par[0][src] = parent;\n for (int j = 1; j < 15; j ++) \n par[j][src] = par[j-1][par[j-1][src]];\n \n for (auto child: g[src]) {\n if (child.F == parent) continue;\n \n frq[child.F] = frq[src];\n frq[child.F][child.S] ++;\n \n Dfs (child.F, src);\n }\n }\n \n int LCA (int u, int v) {\n if (lvl[u] > lvl[v]) swap(u, v);\n \n int diff = lvl[v] - lvl[u];\n for (int j = 0; j < 15; j ++) {\n if (diff & (1 << j)) v = par[j][v];\n }\n \n if (u == v) return u;\n \n for (int j = 14; j >= 0; j --) \n if (par[j][u] != par[j][v]) {\n u = par[j][u];\n v = par[j][v];\n }\n \n return par[0][u];\n }\n \npublic:\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n Reset();\n \n for (auto i : edges) {\n g[i[0]+1].push_back({i[1]+1, i[2]});\n g[i[1]+1].push_back({i[0]+1, i[2]});\n }\n Dfs (1, 0);\n \n vector<int> result;\n for (auto q: queries) {\n int u = q[0] + 1;\n int v = q[1] + 1;\n int lca = LCA(u, v);\n \n vector<int> f(W, 0);\n for (int j = 0; j < W; j ++) \n f[j] = frq[u][j] + frq[v][j] - 2*frq[lca][j];\n \n int mx = 0, sum = 0;\n for (auto i : f) {\n mx = max(mx, i);\n sum += i;\n }\n \n result.push_back(sum - mx);\n }\n \n return result;\n }\n};\n```
16
0
['C++']
0
minimum-edge-weight-equilibrium-queries-in-a-tree
[Python3] binary lifting
python3-binary-lifting-by-ye15-easa
For solutions of weekly 361, please pull this commit. \n\n\nclass Solution:\n def minOperationsQueries(self, n: int, edges: List[List[int]], queries: List[Li
ye15
NORMAL
2023-09-03T04:01:17.188074+00:00
2023-09-06T01:13:41.047459+00:00
791
false
For solutions of weekly 361, please pull this [commit](https://github.com/gaosanyong/leetcode/commit/c21e07fdae41e9dcb60c3845e718c256302215fc). \n\n```\nclass Solution:\n def minOperationsQueries(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]:\n tree = [[] for _ in range(n)]\n for u, v, w in edges: \n tree[u].append((v, w))\n tree[v].append((u, w))\n m = int(log2(n)) + 2\n lift = [[-1]*m for _ in range(n)] # binary lifting \n freq = [[0]*27 for _ in range(n)]\n depth = [-1]*n \n stack = [(0, -1, 0)]\n while stack: \n u, p, d = stack.pop()\n depth[u] = d \n for v, w in tree[u]: \n if v != p: \n lift[v][0] = u\n freq[v][:] = freq[u][:]\n freq[v][w] += 1\n for j in range(1, m): \n if lift[v][j-1] == -1: break \n lift[v][j] = lift[lift[v][j-1]][j-1]\n stack.append((v, u, d+1))\n \n def lca(u, v): \n """Return lowest common ancestor via binary lifting."""\n if depth[u] > depth[v]: u, v = v, u\n for i in range(m): \n if depth[v]-depth[u] & 1<<i: v = lift[v][i]\n if u == v: return u \n for i in range(m-1, -1, -1): \n if lift[u][i] != lift[v][i]: u, v = lift[u][i], lift[v][i]\n return lift[u][0]\n \n ans = []\n for u, v in queries: \n k = lca(u, v)\n count = [freq[u][w] + freq[v][w] - 2*freq[k][w] for w in range(27)]\n ans.append(sum(count) - max(count))\n return ans\n```
15
0
['Python3']
2
minimum-edge-weight-equilibrium-queries-in-a-tree
Euler Tour
euler-tour-by-votrubac-tlnm
This problem is a great brush-up on LCA.\n\nWe can use Tarjan\'s (since we know all queries in advance) or Binary Lifting, but for me, the Euler tour was the mo
votrubac
NORMAL
2023-09-03T23:03:35.171460+00:00
2023-09-03T23:17:00.491534+00:00
767
false
This problem is a great brush-up on LCA.\n\nWe can use Tarjan\'s (since we know all queries in advance) or Binary Lifting, but for me, the Euler tour was the most intuitive approach.\n\nThe important constraint is that the weight is limited to 26. So, we can store the number of edges of each weight from a root (we can pick any node as a root) to each node.\n\nIn the `dfs` function, we do just that, plus we build the `euler` tour. Note that for the Euler tour, we track nodes along the tour, the node height, and a position (any position) of a node in the tour.\n\nTo find LCA for nodes `u` and `v`, we determine their positions in the Euler tour, and find a node with the lowest height between their positions. To do it efficiently (in log n), we use the segment tree.\n\n> Note that the logic, as well as the `build`, `query` and `lca` functions, are taken almost "as-is" from the cp-algorithms web site.\n\nOnce we find LCA, we can use the weight frequency to find the number of edges between `u` and `v`, and the weight that appears most frequently.\n\n**C++**\n```cpp\nvector<array<int, 27>> freq;\nvector<int> height, id, euler, segtree, res;\nvoid dfs(int i, int p, vector<vector<pair<int, int>>> &al, array<int, 27> &f, int h = 0) {\n freq[i] = f;\n height[i] = h;\n id[i] = euler.size();\n euler.push_back(i); \n for (auto [j, w] : al[i]) {\n if (j != p) {\n ++f[w];\n dfs(j, i, al, f, h + 1);\n euler.push_back(i);\n --f[w];\n }\n }\n}\nvoid build(int node, int b, int e) {\n if (b == e)\n segtree[node] = euler[b];\n else {\n int mid = (b + e) / 2;\n build(node << 1, b, mid);\n build(node << 1 | 1, mid + 1, e);\n int l = segtree[node << 1], r = segtree[node << 1 | 1];\n segtree[node] = (height[l] < height[r]) ? l : r;\n }\n}\nint query(int node, int b, int e, int L, int R) {\n if (b > R || e < L)\n return -1;\n if (b >= L && e <= R)\n return segtree[node];\n int mid = (b + e) >> 1;\n int left = query(node << 1, b, mid, L, R);\n int right = query(node << 1 | 1, mid + 1, e, L, R);\n return left == -1 ? right : right == -1 ? left :\n height[left] < height[right] ? left : right;\n}\nint lca(int u, int v) {\n return query(1, 0, euler.size() - 1, min(id[u], id[v]), max(id[u], id[v]));\n} \nvector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n vector<vector<pair<int, int>>> al(n);\n height = id = vector<int>(n);\n freq = vector<array<int, 27>>(n);\n for (const auto &e : edges) {\n al[e[0]].push_back({e[1], e[2]});\n al[e[1]].push_back({e[0], e[2]});\n }\n dfs(0, -1, al, array<int, 27>() = {}); \n segtree.resize(euler.size() * 4);\n build(1, 0, euler.size() - 1);\n for (const auto &q : queries) {\n int u = q[0], v = q[1], a = lca(u, v);\n int total = 0, max_f = 0;\n for (int i = 1; i < 27; ++i) {\n total += freq[u][i] + freq[v][i] - 2 * freq[a][i];\n max_f = max(max_f, freq[u][i] + freq[v][i] - 2 * freq[a][i]);\n }\n res.push_back(total - max_f);\n }\n return res;\n}\n```
12
0
['C']
2
minimum-edge-weight-equilibrium-queries-in-a-tree
Bitmask + graph solution [EXPLAINED]
bitmask-graph-solution-explained-by-r9n-4y15
IntuitionFind the least number of operations to make all paths between queried nodes use the same weight. To do this, we need to calculate the most frequent wei
r9n
NORMAL
2025-01-15T21:51:43.244936+00:00
2025-01-15T21:51:43.244936+00:00
32
false
# Intuition Find the least number of operations to make all paths between queried nodes use the same weight. To do this, we need to calculate the most frequent weight in each path and subtract it from the total edges between the nodes. # Approach I use a graph, queries, and Tarjan's algorithm with disjoint sets to compute the Lowest Common Ancestor (LCA), then count edge weights along paths using prefix sums and calculate results by comparing frequencies from the root to queried nodes. # Complexity - Time complexity: O(n + q + n * w) where n is the number of nodes, q is the number of queries, and w (up to 26) is the range of edge weights; most operations involve visiting each node and edge once or counting weights efficiently. - Space complexity: O(n * w) for storing weight counts for each node and O(n + q) for the graph and query storage, using arrays, dictionaries, and prefix sums efficiently to minimize overhead. # Code ```python3 [] class Solution: def minOperationsQueries(self, n, edges, queries): # Step 1: Build the adjacency list representation of the graph graph = defaultdict(list) for u, v, w in edges: graph[u].append((v, w)) # Add edge from u to v with weight w graph[v].append((u, w)) # Add edge from v to u with weight w (undirected graph) # Step 2: Prepare queries to find the Lowest Common Ancestor (LCA) m = len(queries) # Number of queries query = defaultdict(list) # Stores query pairs for each node for i, (u, v) in enumerate(queries): query[u].append((v, i)) # Add query for node u if u != v: query[v].append((u, i)) # Add reverse query for node v if u != v # Step 3: Initialize Disjoint Set Union (DSU) for Tarjan's algorithm parent = list(range(n)) # Parent array for DSU def find(x): # Path compression to efficiently find the root of a set if x != parent[x]: parent[x] = find(parent[x]) return parent[x] # Step 4: Prepare arrays for weight counts and LCA results cnt = [[0] * 27 for _ in range(n)] # Frequency of weights from root to each node path = [0] * 27 # Temporary array for path weight frequencies lca = [0] * m # Stores the LCA for each query color = [0] * n # Visitation state: 0 - not visited, 1 - visiting, 2 - visited # Step 5: Define Tarjan's LCA algorithm def tarjan(cur, pre): # Store the weight frequency up to the current node cnt[cur] = path[:] color[cur] = 1 # Mark node as visiting # Traverse all adjacent nodes for child, w in graph[cur]: if color[child] != 0: # Skip visited nodes continue path[w] += 1 # Increment the weight count tarjan(child, cur) # Recur for the child node path[w] -= 1 # Decrement the weight count after recursion parent[child] = cur # Union: Set the parent of the child as the current node # Process queries for the current node for node, idx in query[cur]: # If the other node in the query is either the current node or already visited if node == cur or color[node] == 2: lca[idx] = find(node) # Find the LCA of the two nodes color[cur] = 2 # Mark node as fully visited # Start Tarjan's LCA algorithm from the root node (assumed to be 0) tarjan(0, -1) # Step 6: Compute the result for each query result = [] for i, (u, v) in enumerate(queries): total_edges, max_frequency = 0, 0 # Calculate the total and maximum frequency for each weight for j in range(1, 27): # Number of edges of weight j in the path between u and v current_count = cnt[u][j] + cnt[v][j] - 2 * cnt[lca[i]][j] total_edges += current_count # Add to total edge count max_frequency = max(max_frequency, current_count) # Track the maximum frequency # The result is the total edges minus the most frequent weight count result.append(total_edges - max_frequency) return result ```
11
0
['Dynamic Programming', 'Bit Manipulation', 'Depth-First Search', 'Breadth-First Search', 'Graph', 'Topological Sort', 'Memoization', 'Bitmask', 'Strongly Connected Component', 'Python3']
0
minimum-edge-weight-equilibrium-queries-in-a-tree
✅ C++ | Binary Lifting🔥🔥 | LCA | 🚀🚀 Simple🔥 Clean Code | Easy to Understand✅✅
c-binary-lifting-lca-simple-clean-code-e-2q47
Code\n\nclass Solution {\npublic:\n vector<int> depth;\n int weights[10004][27];\n int par[10004][16];\n vector<vector<pair<int, int>>> g;\n void
pkacb
NORMAL
2023-09-03T14:52:02.435827+00:00
2023-09-03T14:56:02.285997+00:00
454
false
# Code\n```\nclass Solution {\npublic:\n vector<int> depth;\n int weights[10004][27];\n int par[10004][16];\n vector<vector<pair<int, int>>> g;\n void dfs(int src, int paren = -1)\n {\n for(auto [child, wt] : g[src])\n {\n if(child == paren)\n continue;\n\n weights[child][wt]++;\n for(int i = 0; i < 27; i++)\n weights[child][i] += weights[src][i];\n\n par[child][0] = src;\n depth[child] = depth[src] + 1;\n dfs(child, src);\n }\n }\n\n int lca(int a, int b)\n {\n if(depth[a] < depth[b])\n swap(a, b);\n \n int diff = depth[a] - depth[b];\n for(int i = 0; i < 16; i++)\n if(diff & (1 << i))\n a = par[a][i];\n\n if(a == b)\n return a;\n \n for(int i = 15; i >= 0; i--)\n {\n if(par[a][i] != par[b][i])\n {\n a = par[a][i];\n b = par[b][i];\n }\n }\n\n return par[a][0];\n }\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n depth.resize(n);\n g.resize(n);\n for(auto edge : edges)\n {\n g[edge[0]].push_back({edge[1], edge[2]});\n g[edge[1]].push_back({edge[0], edge[2]});\n }\n\n dfs(0);\n for(int i = 1; i < 16; i++)\n {\n for(int node = 0; node < n; node++)\n {\n int parent = par[node][i - 1];\n par[node][i] = par[parent][i - 1];\n }\n }\n\n vector<int> ans;\n for(auto query : queries)\n {\n int a = query[0];\n int b = query[1];\n\n int node = lca(a, b);\n int distance = depth[a] + depth[b] - 2 * depth[node];\n // cout << node << " " << distance << endl;\n int maxx = 0;\n for(int i = 0; i < 27; i++)\n maxx = max(maxx, abs(weights[a][i] + weights[b][i] - 2 * weights[node][i]));\n \n ans.push_back(distance - maxx);\n }\n\n return ans;\n }\n};\n```
7
0
['Bit Manipulation', 'Depth-First Search', 'Graph', 'C++']
0
minimum-edge-weight-equilibrium-queries-in-a-tree
Binary lifting for LCA in C++ with Explanation
binary-lifting-for-lca-in-c-with-explana-6s4f
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nWe will store count of
RamKumarGoyal
NORMAL
2023-09-04T08:19:09.458285+00:00
2023-09-04T08:22:16.648798+00:00
364
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe will store count of each type of edge from root node to any node.\nAlso create 2D DP for doing binary lifting.\nFor each query we will find their LCA and then we all edges from root to node1,node2 and common node.So all the edges from node1 to node2 is\n(Edges from Node1) + (Edges from Node2) - 2*(Edges from Common Node).\nAnd answer would be simple -> (Total No of edges - max frequency among edges).\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nFor creating 2D DP for binary lifting is O(nlogn).\nFor each Query it requires only O(logn) as to find LCA and for calculating answer for each query O(26) = O(1).\nFor all queries total O(mlogn).\nTotal Time Complexity -> O(nlogn + mlogn).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThere will be 3 -> 2D DP for storing \n1. 2^i ancestor for jth node dp[j][i] Binary Lifiting\n2. Adjacency list for tree\n3. Count of each type of edge from root to node\n\nAnd 1 1D DP for storing heights of each node considering 0 as root node.\nNote -> Root Node can be any node.\n\n# Code\n```\nclass Solution {\n vector<vector<int>> v;\n vector<vector<int>> dp;\n vector<vector<pair<int,int>>> tree;\n vector<int> height;\npublic:\n void binary_lifting(int node,int parent,vector<int>&v1,int level)\n {\n v[node] = v1;\n dp[node][0] = parent;\n height[node] = level;\n for(int i = 1 ; i < 15 ; ++i)\n if(dp[node][i-1] != -1) dp[node][i] = dp[dp[node][i-1]][i-1]; \n for(auto &x : tree[node])\n {\n if(x.first != parent)\n {\n ++v1[x.second];\n binary_lifting(x.first,node,v1,level+1);\n --v1[x.second];\n }\n }\n }\n int lift(int node,int jump)\n {\n for(int i = 14 ; i >= 0 ; --i)\n {\n if(node == -1) return node;\n if(jump&(1<<i))\n node = dp[node][i];\n }\n return node;\n }\n int ancestor(int a,int b)\n {\n if(height[a] < height[b]) swap(a,b);\n a = lift(a,height[a]-height[b]);\n if(a == b) return a;\n for(int i = 14 ; i >= 0 ; --i)\n {\n if(dp[a][i] != dp[b][i])\n {\n a = dp[a][i];\n b = dp[b][i];\n }\n }\n\t return lift(a,1);\n }\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n int m = queries.size();\n v = vector<vector<int>>(n);\n dp = vector<vector<int>>(n,vector<int>(15,-1));\n tree = vector<vector<pair<int,int>>>(n);\n height = vector<int>(n);\n for(auto &x : edges)\n {\n tree[x[0]].push_back({x[1],x[2]-1});\n tree[x[1]].push_back({x[0],x[2]-1});\n }\n vector<int> v1(26,0);\n binary_lifting(0,-1,v1,0);\n vector<int> ans;\n for(auto &x : queries)\n {\n int k = ancestor(x[0],x[1]);\n vector<int> v2(26,0);\n int maxi(0),s(0);\n for(int i = 0 ; i < 26 ; ++i)\n {\n v2[i] = v[x[0]][i] + v[x[1]][i] - 2*v[k][i];\n s += v2[i];\n maxi = max(maxi,v2[i]);\n }\n ans.push_back(s-maxi);\n }\n return ans;\n }\n};\n```
6
0
['Dynamic Programming', 'Bit Manipulation', 'Tree', 'C++']
2
minimum-edge-weight-equilibrium-queries-in-a-tree
LCA | c++
lca-c-by-betoscl-vryr
Approach \n\nSet the weight by which all edges are to be changed, note that the weight can be at most $w\leq 26$ so we can iterate over all possible weights. \n
BetoSCL
NORMAL
2023-09-03T04:01:33.190927+00:00
2023-09-03T21:02:01.237514+00:00
876
false
# Approach \n\nSet the weight by which all edges are to be changed, note that the weight can be at most $w\\leq 26$ so we can iterate over all possible weights. \n\nNow knowing how many edges with weight $w$ there are in a path is a task similar to obtaining the distance for any pair in a tree, for this we will build a graph for each weight such that for graph $G_w$ we will have an edge of weight $W =1$ if that same edge in the original graph was $w$.\n\nNow we have at most $26$ graphs with edges of weight $1$ so now we only need to know how many ones are in a path, as said we can use the same strategy to obtain the distance and for this we use the $lca$ of $u, v$ then the number of ones will be $Q[w][u]+Q[w][v]-2Q[w][lca]$ where $Q$ is the count of ones from the $root$ to $u$, $root \\rightarrow u$ for graph w $G_w$.\n\nNow the answer will be simply $min_{w=1}^{26} \\; \\;dist(u,v) - numberOnes(u,v,w)$\n\n$dist(u,v)$ is the number of edges in the path\n# Complexity\n$O(|queries| \\times 26 + \\;\\; n\\times log(n))$\n$|queries| \\times 26$ for the queries and $n \\times log(n)$ for the lca computations. \n\n\n# Code\n```\nclass Solution {\npublic:\n int mxlog = 25;\n vector<vector<pair<int,int>>> graph;\n vector<vector<int>> parent;\n vector<int> depth;\n unordered_set<int> W; //A set of all different weights, small optimization maybe don\'t needed. \n \n vector<vector<int>> Q; //Here we save the number of ones from root to u for each possible weight w\n int N;\n void dfs(int u,int p = -1,int d = 0,int q = 0){\n depth[u] = d;\n parent[0][u] = p;\n for(auto v:graph[u]){\n if(v.first== p)continue;\n for(auto q:W){\n if(q == v.second)\n Q[q][v.first] = Q[q][u]+1;\n else \n Q[q][v.first] = Q[q][u];\n }\n dfs(v.first,u,d+1,q+v.second);\n }\n }\n\n // LCA precomputation\n void build(){\n for(int i = 0;i<N;i++)for(int j = 0;j<mxlog;j++)parent[j][i] = -1;\n for(int i = 0;i<N;i++)depth[i]= -1;\n dfs(0);\n for(int i = 0;i<N;i++)\n if(depth[i]== -1)dfs(i);\n\n for(int i = 1;i<mxlog;i++){\n for(int u = 0;u<N;u++){\n if(parent[i-1 ][u]!= -1)\n parent[i][u] = parent[i-1][parent[i-1][u]];\n }\n }\n }\n\n int lca(int u ,int v){\n if(depth[u]>depth[v])swap(u,v);\n int W = depth[v]-depth[u];\n for(int i = mxlog-1;i>=0;i--){\n if(W & (1<<i))\n v = parent[i][v];\n }\n if(u == v)return u; \n\n for(int i = mxlog-1;i>=0;i--){\n if(parent[i][u]!= parent[i][v]){\n u = parent[i][u];\n v = parent[i][v];\n }\n }\n return parent[0][u];\n }\n \n // Get the number of ones in the path from u to v in the graph w\n int numberOnes(int u,int v,int w,int LCA){\n return Q[w][u]+Q[w][v]-(2*Q[w][LCA]);\n }\n \n \n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n N = n;\n graph.resize(n);\n depth.resize(n);\n parent.resize(mxlog,vector<int> (n,-1));\n Q.resize(27,vector<int> (n,0));\n for(int i = 0;i<26;i++){\n Q[i].resize(n);\n }\n \n for(int i = 0;i<edges.size();i++){\n int u = edges[i][0];\n int v = edges[i][1];\n int w = edges[i][2];\n W.insert(w);\n graph[u].push_back({v,w});\n graph[v].push_back({u,w});\n \n }\n \n build();\n \n \n vector<int> ans(queries.size());\n \n \n for(int i = 0;i<queries.size();i++){\n int u = queries[i][0];\n int v = queries[i][1];\n int LCA = lca(u,v);\n int len = depth[u]+depth[v]-(2*depth[LCA]);\n int res = len;\n \n for(auto q:W){\n res = min(res,len- numberOnes(u,v,q,LCA)); \n }\n ans[i] = res;\n }\n return ans;\n }\n};\n```
6
0
['C++']
1
minimum-edge-weight-equilibrium-queries-in-a-tree
C++ solution || LCA by Binary Lifting
c-solution-lca-by-binary-lifting-by-avad-ueh9
\n# Code\n\nclass Solution {\npublic:\n int m;\n void dfs(int i,int par,int level,vector<vector<int>>&table,vector<vector<pair<int,int>>>&adj,vector<vecto
avadhut7969
NORMAL
2023-09-03T12:56:38.651487+00:00
2023-09-03T12:56:38.651506+00:00
59
false
\n# Code\n```\nclass Solution {\npublic:\n int m;\n void dfs(int i,int par,int level,vector<vector<int>>&table,vector<vector<pair<int,int>>>&adj,vector<vector<int>>&w,vector<int>&d){\n d[i]=level;\n table[0][i]=par;\n for(auto it:adj[i]){\n if(it.first==par) continue;\n w[it.first]=w[i];\n w[it.first][it.second]++;\n dfs(it.first,i,level+1,table,adj,w,d);\n }\n }\n void build(vector<vector<int>>&table,int n){\n for(int i=1;i<m;i++){\n for(int j=0;j<n;j++){\n int par=table[i-1][j];\n table[i][j]=table[i-1][par];\n }\n }\n }\n int lca(int x,int y,vector<vector<int>>&table,vector<int>&d){\n if(d[x]>d[y]) return lca(y,x,table,d);\n int k=d[y]-d[x];\n for(int i=0;i<m;i++){\n if((1<<i) & k){\n y=table[i][y];\n }\n }\n for(int i=m-1;i>=0;i--){\n int xp=table[i][x];\n int yp=table[i][y];\n if(xp!=yp){\n x=xp;\n y=yp;\n }\n }\n return x==y?x:table[0][x];\n }\n vector<int> minOperationsQueries(int n,vector<vector<int>>& edges, vector<vector<int>>& queries){\n m=log2(n)+1;\n vector<int>d(n,0);\n vector<vector<int>>w(n);\n vector<vector<pair<int,int>>>adj(n);\n for(auto it:edges){\n adj[it[0]].push_back({it[1],it[2]});\n adj[it[1]].push_back({it[0],it[2]});\n }\n vector<vector<int>>table(m,vector<int>(n));\n w[0]=vector<int>(27,0);\n dfs(0,0,0,table,adj,w,d);\n build(table,n);\n vector<int>ans;\n for(auto it:queries){\n int x=it[0],y=it[1];\n int l=lca(x,y,table,d);\n int len=d[x]+d[y]-2*d[l];\n int maxi=0;\n for(int i=1;i<=26;i++){\n int s=w[x][i]+w[y][i]-2*w[l][i];\n maxi=max(maxi,s);\n } \n ans.push_back(len-maxi);\n }\n return ans;\n }\n};\n```
4
0
['Tree', 'Depth-First Search', 'C++']
0
minimum-edge-weight-equilibrium-queries-in-a-tree
Lowest Common Ancestor
lowest-common-ancestor-by-jeffreyhu8-w1qr
Intuition\nA brute force solution is to find the path from a to b for each query a, b, then find the most common element. This is $O(n\cdot\mathrm{queries.lengt
jeffreyhu8
NORMAL
2023-09-03T04:02:10.607570+00:00
2023-09-03T04:02:10.607592+00:00
600
false
# Intuition\nA brute force solution is to find the path from `a` to `b` for each query `a, b`, then find the most common element. This is $O(n\\cdot\\mathrm{queries.length})$, which is too slow.\n\n# Approach\nProblems involving paths on trees can sometimes be solved using lowest common ancestor (LCA). For instance, the sum of the path from `a` to `b` on a tree is `sum[a] + sum[b] - 2 * sum[lca(a, b)]`, where `sum[i]` is the sum of the edge weights from the root to `i`.\n\nSimilarly, the frequency of edge weight `w` from `a` to `b` can be found as `weightCount[a][w] + weightCount[b][w] - 2 * weightCount[lca(a, b)][w]`.\n\nWe can use this to find the most frequent edge weight on some path quickly, given the low number of possible weights.\n\n# Complexity\n- Time complexity: $$O(n\\lg n + n\\cdot\\mathrm{max}(w_i) + \\mathrm{queries.length}\\cdot\\mathrm{max}(w_i)\\cdot\\lg n)$$\n\n- Space complexity: $$O(n\\lg n + n\\cdot\\mathrm{max}(w_i) + \\mathrm{queries.length})$$\n\n# Code\n```py\nclass Solution:\n def minOperationsQueries(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]:\n # construct adjacency list\n adjList = [set() for _ in range(n)]\n for u, v, w in edges:\n adjList[u].add((v, w))\n adjList[v].add((u, w))\n\n # variables for binary jumping\n nb = n.bit_length()\n\n parent = [[0] * n for _ in range(nb)] # parent[power][i] = the ancestor that is 2^power levels up from i\n parentWeight = [0] * n # parentWeight[i] = the weight of the edge from i to parent[0][i]\n depth = [0] * n\n\n # root the tree, initializing the base case for binary jumping in the process\n def dfs(root: int, d: int) -> None:\n depth[root] = d\n for child, w in adjList[root]:\n parent[0][child] = root\n parentWeight[child] = w\n\n adjList[child].remove((root, w))\n dfs(child, d + 1)\n dfs(0, 0)\n\n # binary jumping\n for i in range(1, nb):\n for j in range(n):\n parent[i][j] = parent[i - 1][parent[i - 1][j]]\n\n def jump(a: int, k: int) -> int:\n res = a\n for i in range(nb):\n if (k & (1 << i)) != 0:\n res = parent[i][res]\n return res\n\n @cache\n def lca(a: int, b: int) -> int:\n if depth[a] < depth[b]:\n a, b = b, a\n\n a = jump(a, depth[a] - depth[b])\n\n # a ancestor\n if a == b:\n return a\n\n for i in reversed(range(nb)):\n if parent[i][a] != parent[i][b]:\n a = parent[i][a]\n b = parent[i][b]\n\n return parent[0][a]\n\n @cache\n def weightCount(i: int, w: int) -> int:\n """Returns the number of edges with weight w from i to the root (0)."""\n if i == 0:\n return 0\n return weightCount(parent[0][i], w) + (1 if parentWeight[i] == w else 0)\n\n res = []\n for a, b in queries:\n operationsRequired = inf\n for w in range(1, 27):\n operationsRequired = min(\n # number of edges from a to b = depth[a] + depth[b] - 2 * depth[lca(a, b)]\n # number of edges with weight w from a to b =\n # weightCount(a, w) + weightCount(b, w) - 2 * weightCount(lca(a, b), w)\n depth[a] + depth[b] - 2 * depth[lca(a, b)] - (weightCount(a, w) + weightCount(b, w) - 2 * weightCount(lca(a, b), w)),\n operationsRequired\n )\n res.append(operationsRequired)\n return res\n```
4
0
['Python3']
1
minimum-edge-weight-equilibrium-queries-in-a-tree
Video Solution | Complete Contest | Explanation With Drawings | In Depth
video-solution-complete-contest-explanat-q442
Intuition, approach, and time complexity dicussed in detail in video solution\nhttps://youtu.be/j3sz5xdYRYg\n\n# Code\nJava\n\nclass Solution {\n List<List<i
Fly_ing__Rhi_no
NORMAL
2023-09-03T17:24:25.448056+00:00
2023-09-03T17:24:25.448079+00:00
321
false
# Intuition, approach, and time complexity dicussed in detail in video solution\nhttps://youtu.be/j3sz5xdYRYg\n\n# Code\nJava\n```\nclass Solution {\n List<List<int[]>> graph;\n int[] parentOf;\n int[] depthLevel;\n int[][] wtFreq;\n int[][] parentOfMatrix;\n public int[] minOperationsQueries(int n, int[][] edges, int[][] queries) {\n graph = new ArrayList<>();//shows how the connections are made in the tree\n parentOf = new int[n];\n depthLevel = new int[n]; //shows depth level of each node\n wtFreq = new int[n][27];//from root to a particular node what is the freq of occurence of a pariticular weight value\n\n for(int i = 0; i < n; i++) {\n graph.add(new ArrayList<>());\n }\n \n //forming the graph or say tree \n for(int[] edge : edges) {\n graph.get(edge[0]).add(new int[]{edge[1], edge[2]});\n graph.get(edge[1]).add(new int[]{edge[0], edge[2]});\n }\n\n populateData(0, -1, 1, new int[27]);\n parentOf[0] = 0;\n //used binary lifting here\n parentOfMatrix = buildparentOfMatrix();\n\n int[] results = new int[queries.length];\n\n for(int q = 0; q < queries.length; q++) {\n int u = queries[q][0];\n int v = queries[q][1];\n int LcaUsingBinaryLifting = LcaUsingBinaryLifting(u, v);\n //total number of weightValues occruring between vertex u and v minus the freq of weightValue occuring maximum number of times between vertex or say node u and v is the answer for the current query\n int maxFreq_U_V = 0, totalWtFreq_U_V = 0;\n\n for(int wtVal = 1; wtVal <= 26; wtVal++) {\n int freq = wtFreq[LcaUsingBinaryLifting][wtVal];\n int freqU = wtFreq[u][wtVal];\n int freqV = wtFreq[v][wtVal];\n\n totalWtFreq_U_V += freqU + freqV - 2 * freq;\n\n if(freqU + freqV - 2 * freq > maxFreq_U_V) {\n maxFreq_U_V = freqU + freqV - 2 * freq;\n }\n }\n\n results[q] = totalWtFreq_U_V - maxFreq_U_V;\n }\n\n return results;\n }\n\n private int LcaUsingBinaryLifting(int u, int v) {\n if(depthLevel[u] > depthLevel[v]) {\n return LcaUsingBinaryLifting(v, u);\n }\n\n int depthLevelDiff = depthLevel[v] - depthLevel[u];\n\n //bring the nodes at the same level, for that start form the more deep node and going their depthLevel difference upward \n for(int bitPos = 0; bitPos < 31; bitPos++) {\n if((depthLevelDiff & (1 << bitPos)) != 0) {\n int parentOfOfV = parentOfMatrix[bitPos][v];\n v = parentOfOfV;\n }\n }\n \n //to check if the one of them is LcaUsingBinaryLifting of other\n //in case u is LcaUsingBinaryLifting of both u and v\n if(u == v) return v;\n\n //starting from root, keep finding the common ancestor \n for(int bitPos = 30; bitPos >= 0; bitPos--) {\n //if there comes a point when there ancesstors are not equal move u and v to their ancestors\n if(parentOfMatrix[bitPos][u] != parentOfMatrix[bitPos][v]) {\n u = parentOfMatrix[bitPos][u];\n v = parentOfMatrix[bitPos][v];\n }\n }\n //finally the lca will be their immediate parent, therefore return it\n return parentOfMatrix[0][v];\n }\n //DFS of graph or say tree\n //populateData is used to populate the depthLevel, parentOf, and wtFreq arrays or say vector which will help us to calculate LcaUsingBinaryLifting and answer the queries\n private void populateData(int node, int par, int level, int[] wts) {\n depthLevel[node] = level;\n parentOf[node] = par;\n\n for(int i = 0; i <= 26; i++) {\n wtFreq[node][i] = wts[i];\n }\n\n for(int[] child : graph.get(node)) {\n if(child[0] == par) continue;\n\n wts[child[1]]++;\n populateData(child[0], node, level + 1, wts);\n wts[child[1]]--;\n }\n }\n\n //binary lifting used here \n private int[][] buildparentOfMatrix() {\n int n = parentOf.length, limit = 31;\n int[][] parMat = new int[limit][n];\n \n //for immediate parents of each node they will be same as that of parent array\n parMat[0] = parentOf;\n \n //form indx to (2 ^ bitPos) upward in the graph or say tree\n for(int bitPos = 1; bitPos < limit; bitPos++) {\n for(int indx = 0; indx < n; indx++) {\n //parent (2^(bitPos-1)) upward\n // currNode----->((2^(bitPos-1)) upward from currNode)(prevParent)----------->(2^(bitPos-1)) upward form prevParent-------->target(parMat[bitPos][indx])((2^(bitPos)) upward from)\n int prevParent = parMat[bitPos - 1][indx];\n parMat[bitPos][indx] = parMat[bitPos - 1][prevParent];\n }\n }\n\n return parMat;\n }\n}\n```
3
0
['Java']
0
minimum-edge-weight-equilibrium-queries-in-a-tree
LCA using Binary Lifting || C++ || DP (Memoization)
lca-using-binary-lifting-c-dp-memoizatio-phzm
\n\n# Code\n\nclass Solution {\npublic:\n int count[10001][27];\n \n void dfs(int u, int p, int **memo, vector<int> &lev, int log, vector<pair<int,int>
071_Prashant
NORMAL
2023-09-03T05:10:58.206342+00:00
2023-09-03T05:14:26.967746+00:00
492
false
\n\n# Code\n```\nclass Solution {\npublic:\n int count[10001][27];\n \n void dfs(int u, int p, int **memo, vector<int> &lev, int log, vector<pair<int,int>> adj[])\n{\n memo[u][0] = p;\n for (int i = 1; i <= log; i++)\n memo[u][i] = memo[memo[u][i - 1]][i - 1];\n for (auto x : adj[u])\n {\n int v = x.first;\n if (v != p)\n {\n lev[v] = lev[u] + 1;\n dfs(v, u, memo, lev, log, adj);\n }\n }\n}\n \n// Function to return the LCA of nodes u and v\nint lca(int u, int v, int log, vector<int> &lev, int **memo)\n{\n if (lev[u] < lev[v])\n swap(u, v);\n \n for (int i = log; i >= 0; i--)\n if ((lev[u] - pow(2, i)) >= lev[v])\n u = memo[u][i];\n if (u == v)\n return u;\n for (int i = log; i >= 0; i--)\n {\n if (memo[u][i] != memo[v][i])\n {\n u = memo[u][i];\n v = memo[v][i];\n }\n }\n return memo[u][0];\n}\n \n \n \nvoid getCount(int n, int par, vector<pair<int,int>> adj[])\n{\n for(int i=0;i<27;i++)\n count[n][i] += count[par][i];\n for(auto x:adj[n])\n {\n if(x.first!=par)\n {\n count[x.first][x.second]++;\n getCount(x.first,n,adj);\n }\n }\n}\n vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {\n memset(count,0,sizeof count);\n vector<pair<int,int>> adj[n];\n for(auto x:edges)\n {\n adj[x[0]].push_back({x[1],x[2]});\n adj[x[1]].push_back({x[0],x[2]});\n }\n getCount(0,0,adj);\n \n int log = 32;\n int **memo = new int *[n + 1];\n for (int i = 0; i < n + 1; i++)\n memo[i] = new int[log + 1];\n\n vector<int> lev(n + 1);\n\n for (int i = 0; i <= n; i++)\n memset(memo[i], -1, sizeof memo[i]);\n dfs(0, 0, memo, lev, log, adj); \n vector<int> ans;\n for(auto x:queries)\n {\n int l = lca(x[0], x[1], log, lev, memo);\n int tot = 0,mx = 0;\n for(int i=0;i<27;i++)\n {\n int cur = count[x[0]][i] + count[x[1]][i] - 2*count[l][i];\n tot+=cur;\n mx = max(mx,cur);\n }\n cout<<endl;\n ans.push_back(tot-mx);\n }\n return ans;\n }\n};\n```\n\nStucked during the contest because I was storing the count of weights from leaf to root not from root to leaf. Later on, realized that this is not a Binary Tree so that approach wouldn\'t be optimal because there are many childern of LCA apart from the 2 that contains our query nodes.\n
3
0
['Dynamic Programming', 'C++']
0