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-number-of-k-divisible-components
Easiest way of solving and Understanding
easiest-way-of-solving-and-understanding-387r
IntuitionApproachComplexity Time complexity: Space complexity: Code
shaik_raj
NORMAL
2024-12-21T13:39:24.002889+00:00
2024-12-21T13:39:24.002889+00:00
32
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 maxKDivisibleComponents( self, n: int, edges: List[List[int]], values: List[int], k: int ) -> int: # Step 1: Create adjacency list from edges adj_list = [[] for _ in range(n)] for node1, node2 in edges: adj_list[node1].append(node2) adj_list[node2].append(node1) # Step 2: Initialize component count component_count = [0] # Use a list to pass by reference # Step 3: Start DFS traversal from node 0 self.dfs(0, -1, adj_list, values, k, component_count) # Step 4: Return the total number of components return component_count[0] def dfs( self, current_node: int, parent_node: int, adj_list: List[List[int]], node_values: List[int], k: int, component_count: List[int], ) -> int: # Step 1: Initialize sum for the current subtree sum_ = 0 # Step 2: Traverse all neighbors for neighbor_node in adj_list[current_node]: if neighbor_node != parent_node: # Recursive call to process the subtree rooted at the neighbor sum_ += self.dfs( neighbor_node, current_node, adj_list, node_values, k, component_count, ) sum_ %= k # Ensure the sum stays within bounds # Step 3: Add the value of the current node to the sum sum_ += node_values[current_node] sum_ %= k # Step 4: Check if the sum is divisible by k if sum_ == 0: component_count[0] += 1 # Step 5: Return the computed sum for the current subtree return sum_ ```
1
0
['Tree', 'Depth-First Search', 'Breadth-First Search', 'Topological Sort', 'Python3']
0
maximum-number-of-k-divisible-components
Runtime 59ms beats 100% Memory 161MB beats 97.47%
runtime-59ms-beats-100-memory-161mb-beat-g1r7
Code
Gabrielkq
NORMAL
2024-12-21T12:39:30.697315+00:00
2024-12-21T12:39:30.697315+00:00
4
false
# Code ```cpp [] class Solution { public: int maxKDivisibleComponents(int &n, vector<vector<int>>& _edges, vector<int>& values, int &k) { vector<vector<int>> edges(n); // optional vector<int> degrees(n); for(int i = 0; i < _edges.size(); i++) { ++degrees[_edges[i][0]]; ++degrees[_edges[i][1]]; } for(int i = 0; i < n; i++) { edges[i].reserve(degrees[i]); edges[i].reserve(degrees[i]); } // end optional for(int i = 0; i < _edges.size(); i++) { edges[_edges[i][0]].push_back(_edges[i][1]); edges[_edges[i][1]].push_back(_edges[i][0]); } int ans = 1; // this is basically a dfs on the leaves while also removing // the edges we visited // and we stop each time we find an intersection // an intersection is a node with 3 or more edges // because we remove the edges, at some point the intersection // disappears, and we can pass it for (int i = 0; i < n; i++) { // we need a leaf if (edges[i].size() != 1) continue; int cnode = i; // we need to merge the leaves with their next element // while the merged node it is still a leaf do next while(edges[cnode].size() == 1) { // instead of storing the values in a long long vector // we can always mod the result by k values[cnode] = values[cnode] % k; // if the result is 0, we found another good component if (values[cnode] == 0) ans++; // we always give the current value to the next node // if the current node is good, we don't need to change anything because the value added is 0 int next = edges[cnode][0]; values[next] += values[cnode]; // we remove the edge between the nodes auto it = std::find(edges[next].begin(), edges[next].end(), cnode); edges[next].erase(it); edges[cnode].clear(); // current node becomes the next one cnode = next; } } return ans; } }; ```
1
0
['C++']
0
maximum-number-of-k-divisible-components
Easy Solution. Easy TO UNderstand using dfs
easy-solution-easy-to-understand-using-d-3sug
IntuitionApproachComplexity Time complexity: O(n) Space complexity: O(n) Code
HYDRO2070
NORMAL
2024-12-21T11:31:50.235839+00:00
2024-12-21T11:31:50.235839+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: $$O(n)$$ - Space complexity: $$O(n)$$ # Code ```cpp [] class Solution { private: vector<vector<int>> adj; vector<bool> visit; int ans = 0; long long int dfs(int node,vector<int>& values,int k){ visit[node] = true; long long int sum = values[node]; for(int i : adj[node]){ if(!visit[i]){ sum += dfs(i,values,k); } } if(sum%(k) == 0){ ans++; return 0; } else return sum; } public: int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) { adj.resize(n); visit.resize(n,false); for(auto arr : edges){ adj[arr[0]].push_back(arr[1]); adj[arr[1]].push_back(arr[0]); } if(dfs(0,values,k) != 0) return 1+ans; return ans; } }; ```
1
0
['C++']
0
maximum-number-of-k-divisible-components
DFS + Modulo Cleaner/Faster Than Ever
dfs-modulo-cleanerfaster-than-ever-by-lo-3xkc
IntuitionApproachComplexity Time complexity: The code exploits DFS for hierarchical traversal, leveraging modular arithmetic to efficiently determine valid c
loinguyen1905
NORMAL
2024-12-21T10:17:33.818193+00:00
2024-12-22T04:51:35.245933+00:00
35
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> ![image.png](https://assets.leetcode.com/users/images/70b7c46a-9908-481a-b34a-e31b4ea608c8_1734842957.2030833.png) # Complexity ![image.png](https://assets.leetcode.com/users/images/09fd444a-570a-4b48-b9db-24a333792375_1734842958.7653968.png) ![image.png](https://assets.leetcode.com/users/images/50755392-997a-4d1b-93aa-72f2d495cae6_1734843009.37562.png) ![image.png](https://assets.leetcode.com/users/images/c2f9efec-1100-45be-b5a0-168f9cf734a8_1734843025.6570761.png) ![image.png](https://assets.leetcode.com/users/images/abab0257-d663-455b-b409-8bc9bb9ec87c_1734843049.4380639.png) - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> The code exploits DFS for hierarchical traversal, leveraging modular arithmetic to efficiently determine valid components. It's optimal for tree-based problems and ensures correctness with O(𝑛) O(n) complexity - Space complexity: # Code ```cpp [] class Solution { public: int ans = 0; int dfs(int num, int& k, vector<int> &values, vector<vector<int>> &vt, int parent) { int total = values[num]; for (const int &x : vt[num]) total += x == parent ? 0 : dfs(x, k, values, vt, num); total %= k; ans += !total; return total; }; int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) { vector<vector<int>> vt(n); for (const vector<int>& edge : edges) { int f = edge.front(), b = edge.back(); vt[f].push_back(b); vt[b].push_back(f); } dfs(0, k, values, vt, 0); return ans; } }; ```
1
0
['C++']
0
maximum-number-of-k-divisible-components
Easy Python | DFS Solution
easy-python-dfs-solution-by-pranav743-teq6
ApproachUse Depth-First Search (DFS) to visit each node and calculate the sum of values for all nodes in the same connected component.After visiting all nodes i
pranav743
NORMAL
2024-12-21T09:48:48.745256+00:00
2024-12-21T09:51:50.191250+00:00
48
false
# Approach Use Depth-First Search (DFS) to visit each node and calculate the sum of values for all nodes in the same connected component. After visiting all nodes in a component, check if the sum of values is divisible by k. If yes, increment the count of such components. # Complexity - Time complexity: $$ O(N) $$ - Space complexity: $$ O(N) $$ # Code ```python3 [] class Solution: def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int: graph = defaultdict(list) visited = set() for x,y in edges: graph[x].append(y) graph[y].append(x) c = 0 def dfs(node): nonlocal c for nei in graph[node]: if nei in visited: continue visited.add(nei) values[node]+=dfs(nei) if values[node] % k == 0: c+=1 return values[node] visited.add(0) dfs(0) return c ```
1
0
['Depth-First Search', 'Graph', 'Python3']
0
maximum-number-of-k-divisible-components
Easy DFS❤️‍🔥DRY RUN❤️‍🔥MILDLY AROUSING🤤🤤
easy-dfsdry-runmildly-arousing-by-intbli-lqtm
IntuitionThe problem asks us to find the maximum number of components in a tree such that the sum of values in each component is divisible by k. The key observa
intbliss
NORMAL
2024-12-21T09:47:27.288798+00:00
2024-12-21T09:47:27.288798+00:00
41
false
### **Intuition** The problem asks us to find the maximum number of components in a tree such that the sum of values in each component is divisible by `k`. The key observation is: 1. **Tree Properties**: A tree is a connected graph without cycles, so we can traverse the tree using Depth First Search (DFS). 2. **Divisibility Check**: If a subtree sum is divisible by `k`, we can count it as a separate component. --- ### **Approach** 1. **Tree Representation**: - Use an adjacency list (`tree`) to represent the tree, where each node has a list of its neighbors. 2. **Depth First Search (DFS)**: - Perform a DFS traversal starting from the root node (assume node `0` is the root). - Calculate the sum of the values in the current subtree. - Check if the subtree sum is divisible by `k`: - If yes, increment the component count and return `0` (as this subtree forms a valid component). - Otherwise, return the calculated subtree sum. 3. **Avoid Integer Overflow**: - Use `long` instead of `int` for calculations, as the values can become very large. 4. **Final Result**: - The number of components divisible by `k` is stored in the `components` array, which is updated during the DFS traversal. --- ### **Dry Run** #### **Input** - `n = 7` - `edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]` - `values = [1000000000,1000000000,1000000000,1000000000,1000000000,1000000000,1000000000]` - `k = 7` #### **Steps** 1. Construct the tree: ``` 0 -> [1, 2] 1 -> [0, 3, 4] 2 -> [0, 5, 6] 3 -> [1] 4 -> [1] 5 -> [2] 6 -> [2] ``` 2. Perform DFS: - Start at node `0`: - Visit child `1`: - Visit child `3`: Subtree sum = `1000000000`. Not divisible by `7`, return `1000000000`. - Visit child `4`: Subtree sum = `1000000000`. Not divisible by `7`, return `1000000000`. - Subtree sum at `1` = `1000000000 + 1000000000 + 1000000000 = 3000000000`. Not divisible by `7`, return `3000000000`. - Visit child `2`: - Visit child `5`: Subtree sum = `1000000000`. Not divisible by `7`, return `1000000000`. - Visit child `6`: Subtree sum = `1000000000`. Not divisible by `7`, return `1000000000`. - Subtree sum at `2` = `1000000000 + 1000000000 + 1000000000 = 3000000000`. Not divisible by `7`, return `3000000000`. - Subtree sum at `0` = `1000000000 + 3000000000 + 3000000000 = 7000000000`. Divisible by `7`, increment components to `1`. #### **Output** - Components divisible by `k`: `1`. --- ### **Complexity** 1. **Time Complexity**: `O(n)` - Each node is visited once during the DFS traversal. - The adjacency list representation ensures efficient traversal. 2. **Space Complexity**: `O(n)` - Space required for the adjacency list. - Recursion stack can go as deep as the height of the tree, which is `O(n)` in the worst case for an unbalanced tree. --- ### **Code** ```java class Solution { public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) { // Step 1: Build the tree using an adjacency list ArrayList<ArrayList<Integer>> tree = new ArrayList<>(); for (int i = 0; i < n; i++) { tree.add(new ArrayList<>()); } for (int[] edge : edges) { tree.get(edge[0]).add(edge[1]); tree.get(edge[1]).add(edge[0]); } // Step 2: Initialize components counter int[] components = new int[1]; // Step 3: Perform DFS dfs(0, -1, tree, values, k, components); // Step 4: Return the result return components[0]; } long dfs(int node, int parent, ArrayList<ArrayList<Integer>> tree, int[] values, int k, int[] components) { long subTreeSum = values[node]; // Use long to avoid overflow // Traverse all children for (int neighbour : tree.get(node)) { if (neighbour != parent) { subTreeSum += dfs(neighbour, node, tree, values, k, components); // Accumulate subtree sums } } // Check divisibility if (subTreeSum % k == 0) { components[0]++; // Increment component count return 0; // Reset the subtree sum } return subTreeSum; // Return the subtree sum for the parent } } ``` ![Screenshot from 2024-07-09 09-56-34.png](https://assets.leetcode.com/users/images/bddce367-e191-491d-b1c4-fed0be1c24f6_1734774436.3867188.png)
1
0
['Java']
2
maximum-number-of-k-divisible-components
100% faster🚀100% efficient ️‍🔥O(n) soln
100-faster100-efficient-on-soln-by-harsh-jo3x
IntuitionReferenceComplexity Time complexity: O(n) Space complexity: O(1) Code
harsh007kumar
NORMAL
2024-12-21T09:39:01.560927+00:00
2024-12-21T09:41:28.885464+00:00
107
false
# Intuition DFS # Reference https://youtu.be/xlgOaIK-inc # Complexity - Time complexity: O(n) - Space complexity: O(1) # Code ```csharp [] public class Solution { // Time O(n)| Space O(1) public int MaxKDivisibleComponents(int n, int[][] edges, int[] values, int k) { List<int>[] g = new List<int>[n]; foreach(var edge in edges) { int u = edge[0], v = edge[1]; if(g[u]==null) g[u] = new(); if(g[v]==null) g[v] = new(); g[u].Add(v); g[v].Add(u); } int countKDivisbleConnectedComponents = 0; DFS(0,-1); return countKDivisbleConnectedComponents; // local helper func (you can create seperate func and pass on graph as param) long DFS(int cur, int parent) { long sum = values[cur]; if(g[cur]!=null) foreach(var adj in g[cur]) if(adj!=parent) sum+=DFS(adj,cur); if(sum%k==0) countKDivisbleConnectedComponents ++; return sum; } } } ``` ![image.png](https://assets.leetcode.com/users/images/8cec812a-5972-4c33-b762-f1e34284f9c3_1734773864.4199564.png)
1
0
['Tree', 'Depth-First Search', 'Graph', 'C++', 'Java', 'C#']
0
maximum-number-of-k-divisible-components
Just Plain Old DFS
just-plain-old-dfs-by-numan947-u6lv
IntuitionUsing DFS, we traverse the tree nodes while maintaining a running sum for each subtree rooted at a node. If the sum of a subtree is a multiple of ( k )
numan947
NORMAL
2024-12-21T09:05:07.471919+00:00
2024-12-21T09:05:07.471919+00:00
20
false
# Intuition Using DFS, we traverse the tree nodes while maintaining a running sum for each subtree rooted at a node. If the sum of a subtree is a multiple of \( k \), it qualifies as a valid component. By counting these components and continuing the DFS, we can calculate the maximum number of valid components the tree can be divided into, ultimately solving the problem. # Code ```python3 [] from collections import defaultdict class Solution: def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int: graph = defaultdict(list) for u, v in edges: graph[u].append(v) graph[v].append(u) count = 0 def dfs(curNode, parent): nonlocal count curSum = values[curNode] for nei in graph[curNode]: if nei != parent: curSum += dfs(nei, curNode) if curSum%k == 0: count+=1 return curSum dfs(0, -1) return count ```
1
0
['Python3']
0
maximum-number-of-k-divisible-components
Real Pure C Solution || Beats 100 % in time and memory
real-pure-c-solution-beats-100-in-time-a-qr7t
ApproachThe Approch of this problem is EasyWe use depth-first-search to compute the sum of each vertice if the sum % k == 0 then the tree for which the vertice
IsaacKingsleyD
NORMAL
2024-12-21T08:56:35.386906+00:00
2024-12-21T08:56:35.386906+00:00
13
false
# Approach <!-- Describe your approach to solving the problem. --> The Approch of this problem is Easy We use depth-first-search to compute the sum of each vertice if the sum % k == 0 then the tree for which the vertice is the root can be valid split and increment the answer After DFS we finally return the answer # Complexity - Time complexity: $$O(m + n)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:$$O(m + n)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> - Auxillary space complexity:$$O(n)$$ # Data Structures and Algorithms Since C doesn't have any standard built in data structure we build our Data Structures Here We Use **Linked List** for Vectors as we only need traversal operations and don't need any random access operations We Use **Depth-First-Search** Algorithm here to traverse the tree ***DO UPVOTE IF THIS HEPLED :)*** # Code ``` #define N 30005 struct Node{ int val; struct Node* next; }; typedef struct Node* Vec; Vec tree[N] = {}; int val[N]; int ans, kval; void push(Vec* l, int value){ Vec newnode = (Vec) malloc(sizeof(struct Node)); newnode -> val = value; newnode -> next = *l; *l = newnode; } void clear(Vec* l){ Vec node = *l; Vec temp; while(node){ temp = node; node = node -> next; free(temp); } *l = NULL; } int dfs(int node, int parent){ int s = val[node]; Vec child = tree[node]; while(child){ if(child -> val != parent){ s += dfs(child -> val, node); } child = child -> next; } s = s % kval; if(s == 0) ans++; return s; } int maxKDivisibleComponents(int n, int** edges, int edgesSize, int* edgesColSize, int* values, int valuesSize, int k) { for(int i = 0; i<n; i++){ val[i] = values[i]; } for(int i = 0; i<edgesSize; i++){ push(tree + edges[i][0], edges[i][1]); push(tree + edges[i][1], edges[i][0]); } ans = 0; kval = k; dfs(0,0); for(int i = 0; i<n; i++){ clear(tree + i); } return ans; } ```
1
0
['Linked List', 'Tree', 'Depth-First Search', 'C']
0
maximum-number-of-k-divisible-components
2872. Maximum Number of K-Divisible Components
2872-maximum-number-of-k-divisible-compo-65k8
IntuitionApproachComplexity Time complexity: Space complexity: Code
AdilShamim8
NORMAL
2024-12-21T08:34:50.229616+00:00
2024-12-21T08:34:50.229616+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 ```python3 [] from collections import defaultdict from typing import List class Solution: def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int: # Build the adjacency list for the tree tree = defaultdict(list) for a, b in edges: tree[a].append(b) tree[b].append(a) # Initialize variables self.components = 0 def dfs(node: int, parent: int) -> int: # Calculate the sum of the subtree rooted at `node` subtree_sum = values[node] for neighbor in tree[node]: if neighbor != parent: subtree_sum += dfs(neighbor, node) # If the subtree sum is divisible by k, it's a valid component if subtree_sum % k == 0: self.components += 1 return 0 # Reset the sum to split the component return subtree_sum # Start DFS from the root node (0 assumed as the root) dfs(0, -1) return self.components ```
1
0
['Python3']
0
maximum-number-of-k-divisible-components
[C++] Easy DFS
c-easy-dfs-by-bora_marian-1mh5
The key observation here is that: 'Sum of values is divisible by k'.The result of the problem is the number of nodes which the sum of the subtree values includi
bora_marian
NORMAL
2024-12-21T08:22:17.620677+00:00
2024-12-21T08:25:04.130975+00:00
43
false
The key observation here is that: 'Sum of values is divisible by k'. The result of the problem is the number of nodes which the sum of the subtree values including the node is divisible by `k`. I used DFS to calculate the sum of the subtree values for each node. # Code ```cpp [] class Solution { vector<int> sum; vector<vector<int>>g; vector<int> visit; public: int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) { g.resize(n); sum.resize(n); visit.resize(n, 0); sum = values; for (int i = 0; i < n - 1; i++) { g[edges[i][0]].push_back(edges[i][1]); g[edges[i][1]].push_back(edges[i][0]); } return dfs(0, k); } int dfs(int node, int K) { visit[node] = 1; int result = 0; for (int i = 0; i < g[node].size(); i++) { int newNode = g[node][i]; if (visit[newNode] == 0) { result += dfs(newNode, K); sum[node] += sum[newNode]; if (sum[node] >= K) sum[node] = sum[node] % K; } } if (sum[node] % K == 0) { result++; } return result; } }; ```
1
0
['C++']
0
maximum-number-of-k-divisible-components
Calculating subtree sums
calculating-subtree-sums-by-crankyinmv-s6ve
Stuff I did The places to cut are unaffected by where the root of the tree is. Calculate subtree sums starting from the leaves. Any node whose subtree sum is a
crankyinmv
NORMAL
2024-12-21T07:44:50.950053+00:00
2024-12-21T07:44:50.950053+00:00
22
false
### Stuff I did - The places to cut are unaffected by where the root of the tree is. - Calculate subtree sums starting from the leaves. - Any node whose subtree sum is a multiple of k is a new component. ### Code ```javascript [] /** * @param {number} n * @param {number[][]} edges * @param {number[]} values * @param {number} k * @return {number} */ var maxKDivisibleComponents = function(n, edges, values, k) { /* Build the adjacency list. */ let adj = Array(n); for(let i=0; i<n; i++) adj[i] = []; for(let [a,b] of edges) { adj[a].push(b); adj[b].push(a); } let stSums = Array(n); const getSums = function(node, parent) { let sum = values[node] % k; for(let i=0; i<adj[node].length; i++) { if(adj[node][i] === parent) continue; sum = (sum+getSums(adj[node][i], node))%k; } stSums[node] = sum; return sum; }; getSums(0, -1); let components = stSums.reduce((acc,val)=>acc+(val%k===0?1:0),0); return components; }; ```
1
0
['JavaScript']
0
maximum-number-of-k-divisible-components
✅C++✅Beats 100%🔥Python🔥|| 🚀🚀Super Simple and Efficient Solution🚀🚀||🔥Python🔥✅C++✅
cbeats-100python-super-simple-and-effici-4ghs
Complexity Time complexity: O(n) Space complexity: O(n) Code
shobhit_yadav
NORMAL
2024-12-21T07:42:26.674800+00:00
2024-12-21T07:42:26.674800+00:00
41
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 maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) { int ans = 0; vector<vector<int>> graph(n); for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; graph[u].push_back(v); graph[v].push_back(u); } dfs(graph, 0, -1, values, k, ans); return ans; } private: long dfs(const vector<vector<int>>& graph, int u, int prev, const vector<int>& values, int k, int& ans) { long treeSum = values[u]; for (const int v : graph[u]) if (v != prev) treeSum += dfs(graph, v, u, values, k, ans); if (treeSum % k == 0) ++ans; return treeSum; } }; ``` ```python [] class Solution: def maxKDivisibleComponents( self, n: int, edges: list[list[int]], values: list[int], k: int, ) -> int: ans = 0 graph = [[] for _ in range(n)] def dfs(u: int, prev: int) -> int: nonlocal ans treeSum = values[u] for v in graph[u]: if v != prev: treeSum += dfs(v, u) if treeSum % k == 0: ans += 1 return treeSum for u, v in edges: graph[u].append(v) graph[v].append(u) dfs(0, -1) return ans ```
1
0
['Depth-First Search', 'Graph', 'C++', 'Python3']
0
maximum-number-of-k-divisible-components
Postorder N-ary Tree
postorder-n-ary-tree-by-shourya_setu-be6s
IntuitionUsing postOrder TraversalApproachapplying the simple postorder traversal on n-ary treeComplexity Time complexity: O(n) Space complexity: O(n) Code
Shourya_Setu
NORMAL
2024-12-21T07:40:10.082817+00:00
2024-12-21T07:40:10.082817+00:00
25
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Using postOrder Traversal # Approach <!-- Describe your approach to solving the problem. --> applying the simple postorder traversal on n-ary tree # 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 ```java [] class Solution { public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) { List<List<Integer>> tree = new ArrayList<>(); for (int i = 0; i < n; i++) { tree.add(new ArrayList<>()); } for (int[] edge : edges) { tree.get(edge[0]).add(edge[1]); tree.get(edge[1]).add(edge[0]); } // Compute total sum of values long totalSum = 0; for (int value : values) { totalSum += value; } // Initialize result to count splits int[] result = new int[1]; // Postorder traversal helper boolean[] visited = new boolean[n]; postorder(0, tree, values, visited, totalSum, k, result); return result[0]; } private static long postorder(int node, List<List<Integer>> tree, int[] values, boolean[] visited, long totalSum, int k, int[] result) { visited[node] = true; // Calculate the sum of the subtree rooted at this node long subtreeSum = values[node]; for (int neighbor : tree.get(node)) { if (!visited[neighbor]) { subtreeSum += postorder(neighbor, tree, values, visited, totalSum, k, result); } } // Check if we can split here long remainingSum = totalSum - subtreeSum; if (subtreeSum % k == 0 && remainingSum % k == 0) { result[0]++; // ***** return 0; } // Return the actual subtree sum to the parent return subtreeSum; } } ```
1
0
['Tree', 'Java']
0
maximum-number-of-k-divisible-components
Java || Beats 93% || Easy to understand || Basic Approach
java-beats-93-easy-to-understand-basic-a-16qm
IntuitionApproachValues: [0,3,4,3,3,3,2,3]Original Tree: Sum Tree: Represents the sum of values of all the child Nodes + value[i] Here we have to count the node
IronEyrie
NORMAL
2024-12-21T07:37:39.943915+00:00
2024-12-21T07:37:39.943915+00:00
57
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach `Values: [0,3,4,3,3,3,2,3]` <!-- Describe your approach to solving the problem. --> Original Tree: ![image.png](https://assets.leetcode.com/users/images/5e974589-a290-46f9-8cb7-e1e575622277_1734766313.3296876.png) Sum Tree: Represents the sum of values of all the child Nodes + `value[i]` ![image.png](https://assets.leetcode.com/users/images/3c7c43a8-c48b-4cb4-b8eb-14d55353aa08_1734766331.41699.png) Here we have to count the nodes for which node value is divisible by k. that's the answer. # 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 ```java [] class Solution { int components = 0; ArrayList<ArrayList<Integer>> adjList; boolean[] visited; public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) { adjList = new ArrayList<>(); for(int i = 0; i < n; i++) { adjList.add(new ArrayList<>()); } visited = new boolean[n]; for(int[] e: edges) { adjList.get(e[0]).add(e[1]); adjList.get(e[1]).add(e[0]); } long ans = dfs(0, values, k); return components; } long dfs(int i, int[] values, int k) { if(visited[i]) return 0; visited[i] = true; long valSum = values[i]; for(int adjInd: adjList.get(i)) { valSum += dfs(adjInd, values, k); } if(valSum % k == 0) components++; return valSum; } } ```
1
0
['Java']
0
maximum-number-of-k-divisible-components
Most Premium Question || Mind Testing || DFS ||
most-premium-question-mind-testing-dfs-b-4gnw
Complexity Time complexity : O(N) Space complexity : O(N) Code
Ashish_Ujjwal
NORMAL
2024-12-21T07:35:58.945006+00:00
2024-12-21T07:35:58.945006+00:00
19
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 dfs(vector<vector<int>>&adj, vector<int>&values, int &k, int &count, int curr, int parent = -1){ long long sum = values[curr]; for(int it: adj[curr]){ if(it != parent) sum += dfs(adj, values, k, count, it, curr); } sum %= k; if(sum == 0) count++; return sum; } int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) { vector<vector<int>>adj(n); for(auto edge: edges){ adj[edge[0]].push_back(edge[1]); adj[edge[1]].push_back(edge[0]); } int cnt = 0; dfs(adj, values, k, cnt, 0); return cnt; } }; ```
1
0
['Tree', 'Depth-First Search', 'C++']
0
maximum-number-of-k-divisible-components
Python Clean Code | Beat 96%
python-clean-code-beat-96-by-yt788-ydiz
Code
yt788
NORMAL
2024-12-21T07:22:38.524901+00:00
2024-12-21T07:22:38.524901+00:00
14
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 maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int: adj = [[] for _ in range(n)] for n1, n2 in edges: adj[n1].append(n2) adj[n2].append(n1) total_splits = 1 def getSubtreeSum(curr: int, parent: int) -> int: nonlocal total_splits currSum = values[curr] for node in adj[curr]: if node == parent: continue subSum = getSubtreeSum(node, curr) if subSum % k == 0: total_splits += 1 else: currSum += subSum return currSum getSubtreeSum(0, -1) return total_splits ```
1
0
['Python3']
0
maximum-number-of-k-divisible-components
My solution :
my-solution-by-sayanyeager-qoyd
IntuitionA tree with n nodes labeled from 0 to n-1. Edges given in pairs [a, b] that connect two nodes, forming the tree structure. Values assigned to each node
sayanyeager
NORMAL
2024-12-21T07:13:53.500197+00:00
2024-12-21T07:13:53.500197+00:00
28
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> A tree with n nodes labeled from 0 to n-1. Edges given in pairs [a, b] that connect two nodes, forming the tree structure. Values assigned to each node. Divisor k — we need to divide the tree into groups such that the sum of values in each group is divisible by k. # Approach Tree Properties: A tree with n nodes has exactly n-1 edges. Removing an edge creates two components. Removing multiple edges can create more components. Valid Split Condition: Each component (group) should have its sum of values divisible by k. # Complexity - Time complexity: O(N) - Space complexity: O(N) # Code ```c [] #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define MAX_NODES 30000 // Node structure for adjacency list typedef struct Node { int vertex; struct Node* next; } Node; // Global variables Node* adj[MAX_NODES]; int count = 0; // Function to add an edge to the adjacency list void addEdge(int a, int b) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->vertex = b; newNode->next = adj[a]; adj[a] = newNode; newNode = (Node*)malloc(sizeof(Node)); newNode->vertex = a; newNode->next = adj[b]; adj[b] = newNode; } long long dfs(int node, int parent, int* values, int k) { long long sum = values[node]; // Explore all neighbors Node* temp = adj[node]; while (temp != NULL) { int neighbor = temp->vertex; if (neighbor != parent) { sum += dfs(neighbor, node, values, k); } temp = temp->next; } if (sum % k == 0) { count++; // Increment valid component count return 0; // Reset sum for this component } return sum; // Return sum if not divisible by k } int maxKDivisibleComponents(int n, int** edges, int edgesSize, int* edgesColSize, int* values, int valuesSize, int k) { // Initialize adjacency list for (int i = 0; i < n; i++) { adj[i] = NULL; } // Build adjacency list for (int i = 0; i < edgesSize; i++) { int a = edges[i][0]; int b = edges[i][1]; addEdge(a, b); } // Reset count for each function call count = 0; // Start DFS from node 0 dfs(0, -1, values, k); // Return the number of valid components return count; } // Free adjacency list memory void freeGraph(int n) { for (int i = 0; i < n; i++) { Node* temp = adj[i]; while (temp != NULL) { Node* toFree = temp; temp = temp->next; free(toFree); } adj[i] = NULL; } } ```
1
0
['Tree', 'Depth-First Search', 'C']
0
maximum-number-of-k-divisible-components
Maxximum Number of k- divisible components
maxximum-number-of-k-divisible-component-0fxn
IntuitionApproachComplexity Time complexity: Space complexity: Code
asawari87
NORMAL
2024-12-21T06:54:21.926253+00:00
2024-12-21T06:54:21.926253+00:00
26
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} n * @param {number[][]} edges * @param {number[]} values * @param {number} k * @return {number} */ function maxKDivisibleComponents(n, edges, values, k) { // Step 1: Build adjacency list const tree = Array.from({ length: n }, () => []); for (const [a, b] of edges) { tree[a].push(b); tree[b].push(a); } // Step 2: Initialize visited set and result counter const visited = new Set(); let result = 0; // Step 3: Define DFS function function dfs(node) { visited.add(node); // Calculate the sum of the current subtree let sum = values[node]; for (const neighbor of tree[node]) { if (!visited.has(neighbor)) { sum += dfs(neighbor); // Recursive DFS call } } // If the sum is divisible by k, form a new component if (sum % k === 0) { result++; return 0; // Reset sum for this component } return sum; // Return the sum to the parent node } // Step 4: Start DFS traversal from node 0 dfs(0); return result; } ```
1
0
['JavaScript']
0
maximum-number-of-k-divisible-components
Maximum Number of k- divisible components
maximum-number-of-k-divisible-components-e0l0
IntuitionThe problem involves finding the maximum number of connected components in a tree where the sum of node values in each component is divisible by 𝑘 k. T
asawari87
NORMAL
2024-12-21T06:51:25.311688+00:00
2024-12-21T06:51:25.311688+00:00
40
false
# Intuition The problem involves finding the maximum number of connected components in a tree where the sum of node values in each component is divisible by 𝑘 k. To achieve this: Tree Structure: A tree is an acyclic connected graph, so removing edges can split it into multiple connected components. Divisibility Condition: By calculating subtree sums, we can determine if removing a subtree would satisfy the divisibility condition (subtree_sum%k=0). The idea is to traverse the tree using DFS, calculate subtree sums, and count how many such sums are divisible by k. Each valid division contributes to the number of components. # Approach 1. Tree Representation: - Build an adjacency list from the input edges to represent the tree efficiently. - Use an array to track visited nodes during DFS. 2. DFS Traversal: - Traverse the tree recursively from a starting node (e.g., node 0). - At each node: - Compute the total sum of the subtree rooted at the current node. - For each child, recursively calculate its subtree sum. Check if the subtree sum is divisible by k. - If yes : Increment the component count. "Remove" the subtree by returning 0 to its parent node (indicating no carry-over sum). 3. Return Results: - The final count of valid components is returned. 4. Handling Overflow: - Use long to store sums to prevent integer overflow when node values or subtree sums are large. # Complexity - Time complexity: O(n) - Space complexity: O(n) # Code ```java [] import java.util.*; class Solution { public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) { // Step 1: Build adjacency list List<List<Integer>> tree = new ArrayList<>(); for (int i = 0; i < n; i++) { tree.add(new ArrayList<>()); } for (int[] edge : edges) { tree.get(edge[0]).add(edge[1]); tree.get(edge[1]).add(edge[0]); } // Step 2: Initialize visited array and result counter boolean[] visited = new boolean[n]; int[] result = {0}; // Step 3: Perform DFS dfs(0, tree, values, k, visited, result); return result[0]; } private long dfs(int node, List<List<Integer>> tree, int[] values, int k, boolean[] visited, int[] result) { visited[node] = true; // Calculate the sum for the current subtree long sum = values[node]; // Use long to handle large sums for (int neighbor : tree.get(node)) { if (!visited[neighbor]) { sum += dfs(neighbor, tree, values, k, visited, result); } } // If the sum is divisible by k, it forms a valid component if (sum % k == 0) { result[0]++; return 0; // Reset sum for this component } return sum; // Return the sum to the parent node } } ```
1
0
['Java', 'JavaScript']
0
maximum-number-of-k-divisible-components
📚 BUILD YOUR INTUITION! 📚 O(n log n) ==> O(n) - CREATIVE SOLUTION + CHALLENGE FOR YOU 🔥🔥🔥
build-your-intuition-on-log-n-on-creativ-th9m
IntuitionFirstly, notice that whenever we remove an edge, we split the graph into two components. After removing an edge, we will end up with a whole subtree (t
chinese_spy
NORMAL
2024-12-21T06:48:20.282519+00:00
2024-12-21T06:57:54.677582+00:00
16
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Firstly, notice that whenever we remove an edge, we split the graph into two components. After removing an edge, we will end up with a whole subtree (this can be a singular node), and a PARTIAL subtree. Now, if the sum of all node values in the subtree is divisible by k, then we can add 1 to our answer. Initially, my first thought was to simply go from the bottom of the tree to the top of the tree, and see if each subtree sum is divisible by K. If it is, we should add 1 to our answer, and update previous the subtree sum of all ancestors. This is so that when we go up the tree, we will only consider the PARTIAL subtrees and not the entire subtree. Using the first example from the problem statement to explain this approach: $$k = 6$$ LHS - original tree with each node's value RHS - value of each node is the sum of its subtree on the original (LHS) tree. ![image.png](https://assets.leetcode.com/users/images/84dd43f6-ddae-4437-8130-a2562e471be4_1734762294.7767997.png) On the RHS tree, we traverse to 4 on the bottom left, then 1, then 6, and we realise we can separate the circled part in red, because 6 is divisible by 6. So we add 1 to our answer (now it is equal to 1). We update the subtree sum of the root node from 18 to 12 using our segment tree. Graphically, we are left with the partial subtree below. ![image.png](https://assets.leetcode.com/users/images/98d766fd-df35-4bcf-af68-90aa95c38280_1734762380.243379.png) Then we go to 4 on the right, and finally up to the root node 12. We realise 12 is divisible by 6, so we can separate this part and add 1 to our answer. There is no more tree left. Final return value is 2, which is expected. The time complexity of this approach is:$$O(n \times\log n)$$ (Using lazy range update) Now comes an important observation: Recall that if we ever separate a subtree, the subtree sum is divisible by k = 6. So, if an ancestor subtree has a subtree sum that is also divisible by 6, removing any child subtree will not affect the divisibility - it will still be divisible by 6. From the above example: we initially had a sum of 18 on the root subtree, and after we removed a child subtree with a sum of 6, we were left with a sum of 12 on the partial subtree. Notice how the sums are divisible by 6 both before and after. So we actually don't need to update the sums, and thus we also don't have to traverse from the bottom of the tree upwards. But I was already 60% done coding this range update segment tree solution at this point, so I decided to continue and just omit the range update part. # Approach <!-- Describe your approach to solving the problem. --> **Prerequisites:** You will have trouble understanding the solution if you do not have a solid understanding of the below concepts. - Euler Tour: https://usaco.guide/gold/tree-euler - Segment Tree (Build and Query): https://www.youtube.com/watch?v=-dUiRtJ8ot0 I used a Segment Tree to obtain the range sum of the flattened tree array (obtained via. Euler Tour) - in hindsight, it would have been better to simply use a prefix sum array, because we actually don't have to update the sums, as previously explained. Not only will that consume less memory (although it will be similar asymptotically), but more importantly, it will reduce the Time Complexity to O(n). I trust your intelligence to go and try implement the prefix sum solution by yourself! And feel free to post it in the comments! # Complexity - Time complexity: $$O(n \times\log 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 [] #define ll long long class Solution { private: vector<ll> sek; // Condensed Segment Tree array vector<vector<int>> adj; // Adjacency list vector<int> tour_in; // Start of range for the subtree in flattened tree array vector<int> tour_out; // End of range (EXCLUSIVE) for the subtree in flattened tree array vector<int> tour_vals; // Flattened tree array vector<int> values; // Normal Tree array int timer = 0; public: // Typical Euler Tour - used to flatten the tree // so we can build a segtree on top of it void tour(int node, int par) { tour_in[node] = timer; tour_vals[tour_in[node]] = values[node]; ++timer; for (int nei : adj[node]) { if (nei != par) { tour(nei, node); } } tour_out[node] = timer; } // Typical Segment Tree void build(int idx, int l, int r) { if (l == r) { sek[idx] = tour_vals[l]; return; } int mid = l + (r - l) / 2; build(idx * 2 + 1, l, mid); build(idx * 2 + 2, mid + 1, r); sek[idx] = sek[idx * 2 + 1] + sek[idx * 2 + 2]; } ll query(int idx, int l, int r, int ql, int qr) { if (l > qr || r < ql) { return 0; } if (ql <= l && r <= qr) { return sek[idx]; } int mid = l + (r - l) / 2; ll left = query(idx * 2 + 1, l, mid, ql, qr); ll right = query(idx * 2 + 2, mid + 1, r, ql, qr); return left + right; } int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) { // Resize and initialise global variables adj.resize(n); sek.resize(4 * n); tour_in.resize(n); tour_out.resize(n); this -> values = values; // Build adjacency list for (auto& edge : edges) { int u = edge[0], v = edge[1]; adj[u].push_back(v); adj[v].push_back(u); } tour_vals.resize(n); tour(0, -1); // Perform Euler Tour build(0, 0, n - 1); // Build SegTree int ret = 0; // Set return value initially to 0 for (int i = 0; i < n; ++i) // For each subtree... { // Find the subtree sum ll summ = query(0, 0, n - 1, tour_in[i], tour_out[i] - 1); // If subtree sum divisible by k, add 1 to current return value. if (summ % k == 0) ++ret; } return ret; } }; ``` ![image.png](https://assets.leetcode.com/users/images/a7b15f30-d628-4eb6-943a-39027713e0fe_1734763786.4449728.png)
1
0
['Segment Tree', 'Prefix Sum', 'C++']
0
maximum-number-of-k-divisible-components
C++ DFS Solution
c-dfs-solution-by-vikas_verma-qf6m
IntuitionStarting from a node, reach the leafs of the tree, and start adding the values and return the sum value to parent node. If the value becomes divisible
vikas_verma
NORMAL
2024-12-21T06:29:40.322507+00:00
2024-12-21T06:37:15.303114+00:00
34
false
# Intuition Starting from a node, reach the leafs of the tree, and start adding the values and return the sum value to parent node. If the value becomes divisible by `k` at a node (subtree sum is divisible by k) increament `count` (as we found a valid split) and return 0 sum value instead. The final `count` is the max number of valid components. # Code ```cpp [] class Solution { public: long long dfs(int n, vector<vector<int>>& paths, vector<bool>& visited, vector<int>& values, int &k, int &count){ visited[n]=true; long long sum = values[n]; for(int &next:paths[n]){ if (!visited[next]) sum += dfs(next, paths, visited, values, k, count); } if(sum%k==0) { count+=1; return 0; } return sum; } int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) { vector<bool> visited(n,false); vector<vector<int>> paths(n); for(auto &e:edges) { paths[e[0]].emplace_back(e[1]); paths[e[1]].emplace_back(e[0]); } int count = 0; dfs(0, paths, visited, values, k, count); return count; } }; ```
1
0
['Tree', 'Depth-First Search', 'C++']
0
maximum-number-of-k-divisible-components
Easy Solution, DFS
easy-solution-dfs-by-dotuangv-vtbz
IntuitionApproachComplexity Time complexity: O(n) Space complexity: O(n) Code
dotuangv
NORMAL
2024-12-21T05:49:39.374072+00:00
2024-12-21T05:49:39.374072+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: 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 ans = 0; int dfs(int i, vector<vector<int>>& path, vector<int>& values, vector<bool> &visited, int k){ if(visited[i]) return 0; visited[i] = true; int sum = values[i] % k; for(int j = 0; j < path[i].size(); j++){ sum += dfs(path[i][j], path, values, visited, k); sum %= k; } if(sum % k == 0){ ans++; return 0; } return sum; } int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) { vector<vector<int>> path(n); for(int i = 0; i < edges.size(); i++){ path[edges[i][0]].push_back(edges[i][1]); path[edges[i][1]].push_back(edges[i][0]); } vector<bool> visited(n); dfs(0, path, values, visited, k); return ans; } }; ```
1
0
['Depth-First Search', 'C++']
0
maximum-number-of-k-divisible-components
Simple DFS solution works 😤
simple-dfs-solution-works-by-deepsalunkh-yusv
Problem RestatementYou are given: A tree with n nodes (an undirected connected graph with n-1 edges). An array values of size n, where values[i] represents the
deepsalunkhee
NORMAL
2024-12-21T05:42:32.581859+00:00
2024-12-21T05:42:32.581859+00:00
15
false
### Problem Restatement You are given: - A tree with `n` nodes (an undirected connected graph with `n-1` edges). - An array `values` of size `n`, where `values[i]` represents the value of the `i-th` node. - An integer `k`. **Objective**: Determine the maximum number of components that can be created by removing some edges such that each component's sum of node values is divisible by `k`. --- ### Observations 1. The sum of all node values is guaranteed to be divisible by `k`. 2. To maximize the number of components: - Remove edges strategically so that the resulting components satisfy the condition. --- ### Approach 1. **DFS-Based Solution**: - Use DFS to compute the total sum of values for every subtree. - For every subtree: - If the sum of the subtree is divisible by `k`, it forms a valid component. - Reset the sum to `0` and increment the count of components. 2. **Tree Representation**: - Represent the tree using an adjacency list. 3. **Steps**: - Build an adjacency list from the input edges. - Perform a DFS starting from the root node (`0`), passing the parent node to avoid revisiting it. - At each node: - Calculate the subtree sum. - Check if the sum is divisible by `k`. --- ### Complexity - **Time Complexity**: \( O(n) \) - DFS visits each node and edge once. - **Space Complexity**: \( O(n) \) - For adjacency list and recursive stack. --- ### Code ```java [] class Solution { private long[] dfs(int node, int parent, List<List<Integer>> tree, int k, int[] values) { long sum = 0; long comp = 0; for (Integer x : tree.get(node)) { if (x != parent) { long[] temp = dfs(x, node, tree, k, values); sum += temp[0]; comp += temp[1]; } } sum += values[node]; if (sum % k == 0) return new long[]{0L, comp + 1L}; return new long[]{sum, comp}; } public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) { // Construct adjacency list List<List<Integer>> tree = new ArrayList<>(); for (int i = 0; i < n; i++) { tree.add(new ArrayList<>()); } for (int[] x : edges) { int s = x[0]; int e = x[1]; tree.get(s).add(e); tree.get(e).add(s); } long[] ans = dfs(0, -1, tree, k, values); return (int) ans[1]; } } ``` ``` C++ [] class Solution { private: pair<long, long> dfs(int node, int parent, vector<vector<int>>& tree, int k, vector<int>& values) { long sum = 0; long comp = 0; for (int x : tree[node]) { if (x != parent) { auto temp = dfs(x, node, tree, k, values); sum += temp.first; comp += temp.second; } } sum += values[node]; if (sum % k == 0) return {0L, comp + 1L}; return {sum, comp}; } public: int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) { // Construct adjacency list vector<vector<int>> tree(n); for (auto& edge : edges) { int s = edge[0]; int e = edge[1]; tree[s].push_back(e); tree[e].push_back(s); } auto ans = dfs(0, -1, tree, k, values); return (int) ans.second; } }; ```
1
0
['C++', 'Java']
0
maximum-number-of-k-divisible-components
leetcodedaybyday - Beats 80,49% with Python3 and Beats 36,71% with C++
leetcodedaybyday-beats-8049-with-python3-rir0
IntuitionThe task requires finding the maximum number of components in a tree such that the sum of node values in each component is divisible by ( k ). The key
tuanlong1106
NORMAL
2024-12-21T05:34:59.804232+00:00
2024-12-21T05:34:59.804232+00:00
15
false
# **Intuition** The task requires finding the maximum number of components in a tree such that the sum of node values in each component is divisible by \( k \). The key observation is that whenever a subtree's total sum is divisible by \( k \), it can form a valid component. The problem can be efficiently solved using Depth First Search (DFS) to calculate the sum of values for each subtree. --- # **Approach** 1. **Build an Adjacency List**: - Represent the tree as an adjacency list for easier traversal. 2. **Depth First Search (DFS)**: - Start DFS traversal from the root (node `0`). - For each node, calculate the total sum of its subtree, including its own value. - If the subtree's total sum is divisible by \( k \), increment the result counter (`res`) and reset the total for that subtree to \( 0 \). 3. **Return the Result**: - After completing the DFS traversal, the result counter will contain the number of valid components. --- # **Complexity** - **Time Complexity**: \( O(n) \), where \( n \) is the number of nodes in the tree: - Building the adjacency list takes \( O(n) \). - DFS traversal processes each node and edge once, which is \( O(n) \) for a tree. - **Space Complexity**: \( O(n) \): - The adjacency list requires \( O(n) \) space. - The recursion stack for DFS requires \( O(h) \) space, where \( h \) is the height of the tree (at most \( O(n) \) for a skewed tree). --- # Code ```python3 [] class Solution: def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int: adj = defaultdict(list) for node1, node2 in edges: adj[node1].append(node2) adj[node2].append(node1) res = 0 def DFS(cur, parent): total = values[cur] for child in adj[cur]: if child != parent: total += DFS(child, cur) if total % k == 0: nonlocal res res += 1 return total DFS(0, -1) return res ``` ```cpp [] class Solution { public: int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) { unordered_map<int, vector<int>> adj; for (const auto& edge : edges){ adj[edge[0]].push_back(edge[1]); adj[edge[1]].push_back(edge[0]); } int res = 0; DFS(0, -1, adj, values, k, res); return res; } private: long long DFS(int cur, int parent, unordered_map<int, vector<int>>& adj, vector<int>& values, int k, int& res){ long long total = values[cur]; for (int child : adj[cur]){ if (child != parent){ total += DFS(child, cur, adj, values, k , res); } } if (total % k == 0){ res++; return 0; } return total; } }; ```
1
0
['C++', 'Python3']
0
maximum-number-of-k-divisible-components
TopoSort and BFS
toposort-and-bfs-by-dikshith12345ty-9act
IntuitionApproachCheck the degrees of node if its 1 it's leafnode check the condition if it satisfies cnt+1 or add the value to its neighbiur nodeComplexity Tim
dikshith12345ty
NORMAL
2024-12-21T03:59:44.732831+00:00
2024-12-21T03:59:44.732831+00:00
50
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> Check the degrees of node if its 1 it's leafnode check the condition if it satisfies cnt+1 or add the value to its neighbiur node # 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 maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) { if(n<2){ return 1; } vector<vector<int>> grph(n); vector<int> indegree(n,0); vector<long long> nodevals(values.begin(),values.end()); for(auto e:edges){ int u=e[0],v=e[1]; grph[u].push_back(v); grph[v].push_back(u); indegree[u]++; indegree[v]++; } queue<int> q; for(int i=0;i<indegree.size();i++){ if(indegree[i]==1){ q.push(i); } } int componentcnt=0; while(!q.empty()){ int curr=q.front(); q.pop(); long long addvalue=nodevals[curr]%k==0?0:nodevals[curr]; if(addvalue==0)componentcnt++; for(auto neighbournode:grph[curr]){ if(indegree[neighbournode]>0){ indegree[neighbournode]--; nodevals[neighbournode]+=addvalue; if(indegree[neighbournode]==1)q.push(neighbournode); } } } return componentcnt; } }; ```
1
0
['C++']
0
maximum-number-of-k-divisible-components
easy DFS solution C | Runtime Beats 100.00% | Memory Beats 100.00%
easy-dfs-solution-c-runtime-beats-10000-qqgph
Intuition/ApproachAny node can be the parent node so we will choose zero to be the parent. Keep track of all connections to each node and travel down them. Once
JoshDave
NORMAL
2024-12-21T03:57:50.873853+00:00
2024-12-21T04:00:24.819869+00:00
44
false
# Intuition/Approach Any node can be the parent node so we will choose zero to be the parent. Keep track of all connections to each node and travel down them. Once at a node with no more children, check to see if it could be cut (divisible by k). If not then add it to its parent node and see if the parent node can be cut now. This is the principle of depth first search. *Upvote if this helped* # Complexity - Time complexity: O(n) - Space complexity: O(n) # Code ```c [] struct vector { int* array; int size; }; void vector_push(struct vector* base, int value) { base->array = (int*)realloc(base->array, (base->size + 1) * sizeof(int)); base->array[base->size] = value; ++base->size; } int dfs(int node, int parent, struct vector* adjacent_edges, int* values, int k, int* matches, int n) { int sum = 0; int neighbor_nodes = adjacent_edges[node].size; for (int i = 0; i < neighbor_nodes; ++i) { int neighbor_node = adjacent_edges[node].array[i]; if (neighbor_node == parent) continue; sum += dfs(neighbor_node, node, adjacent_edges, values, k, matches, n); } sum += values[node]; sum %= k; if (sum == 0) ++*matches; return sum; } int maxKDivisibleComponents(int n, int** edges, int edgesSize, int* edgesColSize, int* values, int valuesSize, int k) { // 2d array for neighbors of nodes struct vector* adjacent_edges = (struct vector*)malloc(n * sizeof(struct vector)); for (int i = 0; i < n; ++i) adjacent_edges[i] = (struct vector){(int*)malloc(0 * sizeof(int)), 0}; for (; edgesSize; ++edges, --edgesSize) { int first_node = (*edges)[0], second_node = (*edges)[1]; vector_push(adjacent_edges + first_node, second_node); vector_push(adjacent_edges + second_node, first_node); } int matches = 0; dfs(0, -1, adjacent_edges, values, k, &matches, n); return matches; } ``` *Leave a comment if you have any suggestions*
1
0
['Tree', 'Depth-First Search', 'C']
0
maximum-number-of-k-divisible-components
typescript solution
typescript-solution-by-lainhdev-z4x7
IntuitionApproachComplexity Time complexity: Space complexity: Code
lainhdev
NORMAL
2024-12-21T02:18:17.473078+00:00
2024-12-21T02:18:17.473078+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 ```typescript [] function maxKDivisibleComponents(n: number, edges: number[][], values: number[], k: number): number { // 1. Build the Adjacency List const adj: number[][] = Array.from({ length: n }, () => []); for (const [u, v] of edges) { adj[u].push(v); adj[v].push(u); } // 2. Initialize Count and Visited Array let count = 0; const visited: boolean[] = Array(n).fill(false); // 3. DFS Function function dfs(u: number): number { visited[u] = true; let subtreeSum = values[u]; for (const v of adj[u]) { if (!visited[v]) { subtreeSum += dfs(v); } } // 4. Check for Divisibility and Increment Count if (subtreeSum % k === 0) { count++; return 0; // Reset subtree sum for components above } else { return subtreeSum; } } // 5. Start DFS from the Root (Node 0) dfs(0); // 6. Return the Maximum Number of Components return count; } ```
1
0
['TypeScript']
0
max-increase-to-keep-city-skyline
[C++/Java/Python] Easy and Concise Solution
cjavapython-easy-and-concise-solution-by-z94u
Idea:\nFor grid[i][j], it can\'t be higher than the maximun of its row nor the maximum of its col.\nSo the maximum increasing height for a building at (i, j) is
lee215
NORMAL
2018-03-25T03:19:22.654182+00:00
2018-10-26T21:40:04.551439+00:00
25,158
false
**Idea:**\nFor ```grid[i][j]```, it can\'t be higher than the maximun of its row nor the maximum of its col.\nSo the maximum increasing height for a building at ```(i, j)``` is ```min(row[i], col[j]) - grid[i][j]```\n\n**Codes:**\n```row```: maximum for every row\n```col```: maximum for every col\nThe fisrt loop of grid calcule maximum for every row and every col.\nThe second loop calculate the maximum increasing height for every building.\n\n**Complexity**\nO(N^2)\n\nC++\n```\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n = grid.size();\n vector<int> col(n, 0), row(n, 0);\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n row[i] = max(row[i], grid[i][j]);\n col[j] = max(col[j], grid[i][j]);\n }\n }\n int res = 0;\n for (int i = 0; i < n; i++)\n for (int j = 0; j < n; j++)\n res += min(row[i], col[j]) - grid[i][j];\n return res;\n }\n```\nJava:\n```\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int n = grid.length;\n int[] col = new int[n], row = new int[n];\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n row[i] = Math.max(row[i], grid[i][j]);\n col[j] = Math.max(col[j], grid[i][j]);\n }\n }\n int res = 0;\n for (int i = 0; i < n; i++)\n for (int j = 0; j < n; j++)\n res += Math.min(row[i], col[j]) - grid[i][j];\n return res;\n }\n```\nPython:\n```\n def maxIncreaseKeepingSkyline(self, grid):\n row, col = map(max, grid), map(max, zip(*grid))\n return sum(min(i, j) for i in row for j in col) - sum(map(sum, grid))
201
0
[]
37
max-increase-to-keep-city-skyline
Python solution - Easy, fast, with comments
python-solution-easy-fast-with-comments-1jjjx
python\nclass Solution:\n def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:\n \n N = len(grid) # Height\n M = len
vvenzin
NORMAL
2019-06-03T19:18:08.360288+00:00
2019-06-03T19:18:08.360334+00:00
2,646
false
```python\nclass Solution:\n def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:\n \n N = len(grid) # Height\n M = len(grid[0]) # Width\n \n # Transpose grid: Interchange rows and columns\n grid_t = zip(*grid)\n \n # Vertical and horizontal skylines\n sk_v = [max(row) for row in grid] # As seen from left/right\n sk_h = [max(row) for row in grid_t] # As seen from top/bottom\n \n res = 0\n for i in range(N): # Rows of original grid\n for j in range(M): # Columns of original grid\n # The new building cannot be higher than either skylines\n diff = min(sk_h[j], sk_v[i]) - grid[i][j]\n res += diff\n return res\n```
22
0
['Python']
6
max-increase-to-keep-city-skyline
C++ Simple and Short Solution, Faster than 98%
c-simple-and-short-solution-faster-than-uu294
\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n = grid.size(), res = 0;\n vector<int> rows(n),
yehudisk
NORMAL
2021-07-25T14:14:20.132638+00:00
2021-07-25T14:14:20.132679+00:00
2,120
false
```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n = grid.size(), res = 0;\n vector<int> rows(n), cols(n);\n \n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n rows[i] = max(rows[i], grid[i][j]);\n cols[j] = max(cols[j], grid[i][j]);\n }\n }\n \n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n res += min(rows[i], cols[j]) - grid[i][j];\n }\n }\n \n return res;\n }\n};\n```\n**Like it? please upvote!**
16
0
['C']
4
max-increase-to-keep-city-skyline
Python 3 (two lines) (beats ~100%)
python-3-two-lines-beats-100-by-junaidma-ilv8
```\nclass Solution:\n def maxIncreaseKeepingSkyline(self, G: List[List[int]]) -> int:\n M, N, R, C = len(G), len(G[0]), [max(r) for r in G], [max(c)
junaidmansuri
NORMAL
2019-12-07T08:09:25.459478+00:00
2019-12-07T08:11:23.231434+00:00
1,774
false
```\nclass Solution:\n def maxIncreaseKeepingSkyline(self, G: List[List[int]]) -> int:\n M, N, R, C = len(G), len(G[0]), [max(r) for r in G], [max(c) for c in zip(*G)]\n return sum(min(R[i],C[j]) - G[i][j] for i,j in itertools.product(range(M),range(N)))\n\t\t\n\t\t\n- Junaid Mansuri\n- Chicago, IL
15
8
['Python', 'Python3']
2
max-increase-to-keep-city-skyline
Beginner Friendly Easy Approach || Beats Everyone(100%) || All Popular Languages
beginner-friendly-easy-approach-beats-ev-10to
\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nStore maximum of each row and column\n\n# Approach\n Describe your approach to so
Garv_Virmani
NORMAL
2024-05-29T09:33:50.540617+00:00
2024-05-29T09:35:16.992938+00:00
611
false
![image.png](https://assets.leetcode.com/users/images/b73566e5-3725-4e96-acdd-14bfa7ced108_1716973989.1319396.png)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nStore maximum of each row and column\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nGREEDY\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N^2)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n=grid.size(); //n*n\n //Store max of each row and col in vectors\n vector<int>row(n,INT_MIN);\n vector<int>col(n,INT_MIN);\n for(int r=0;r<n;r++){\n for(int c=0;c<n;c++){\n row[r]=max(row[r],grid[r][c]);\n col[c]=max(col[c],grid[r][c]);\n }\n }\n //visit every grid[r][c] and add min(row[r],col[c])-grid[r][c] to the ans\n int ans=0;\n for(int r=0;r<n;r++){\n for(int c=0;c<n;c++){\n ans+=min(row[r],col[c])-grid[r][c];\n }\n }\n return ans;\n }\n};\n```\n```javascript []\nclass Solution {\n maxIncreaseKeepingSkyline(grid) {\n const n = grid.length;\n // Store max of each row and col in arrays\n const row = new Array(n).fill(Number.MIN_SAFE_INTEGER);\n const col = new Array(n).fill(Number.MIN_SAFE_INTEGER);\n for(let r = 0; r < n; r++){\n for(let c = 0; c < n; c++){\n row[r] = Math.max(row[r], grid[r][c]);\n col[c] = Math.max(col[c], grid[r][c]);\n }\n }\n // Visit every grid[r][c] and add min(row[r], col[c]) - grid[r][c] to the ans\n let ans = 0;\n for(let r = 0; r < n; r++){\n for(let c = 0; c < n; c++){\n ans += Math.min(row[r], col[c]) - grid[r][c];\n }\n }\n return ans;\n }\n}\n```\n```Python []\nclass Solution:\n def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:\n n = len(grid)\n\n # Find the maximum elements in each row and column\n row_max = [max(row) for row in grid]\n col_max = [max(col) for col in zip(*grid)] # Efficient zip for columns\n\n # Calculate the total increase while maintaining the skyline\n total_increase = 0\n for r in range(n):\n for c in range(n):\n total_increase += min(row_max[r], col_max[c]) - grid[r][c]\n\n return total_increase\n\n```\n```Java []\nimport java.util.stream.IntStream;\n\npublic class Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int n = grid.length;\n\n // Find the maximum elements in each row and column efficiently using streams\n int[] rowMax = IntStream.range(0, n)\n .map(r -> IntStream.of(grid[r]).max().orElse(0)) // Efficiently find row max using stream\n .toArray();\n int[] colMax = IntStream.range(0, n)\n .map(c -> IntStream.range(0, n).map(r -> grid[r][c]).max().orElse(0)) // Efficiently find col max using stream\n .toArray();\n\n // Calculate the total increase while maintaining the skyline\n int totalIncrease = 0;\n for (int r = 0; r < n; r++) {\n for (int c = 0; c < n; c++) {\n totalIncrease += Math.min(rowMax[r], colMax[c]) - grid[r][c];\n }\n }\n\n return totalIncrease;\n }\n}\n```\n```C []\n#include <stdio.h>\n#include <limits.h>\n\nint maxIncreaseKeepingSkyline(int grid[][50], int n) {\n int row_max[n], col_max[n];\n\n // Initialize row and column maximums\n for (int i = 0; i < n; i++) {\n row_max[i] = col_max[i] = INT_MIN;\n }\n\n // Find the maximum elements in each row and column\n for (int r = 0; r < n; r++) {\n for (int c = 0; c < n; c++) {\n row_max[r] = fmax(row_max[r], grid[r][c]);\n col_max[c] = fmax(col_max[c], grid[r][c]);\n }\n }\n\n // Calculate the total increase while maintaining the skyline\n int total_increase = 0;\n for (int r = 0; r < n; r++) {\n for (int c = 0; c < n; c++) {\n total_increase += fmin(row_max[r], col_max[c]) - grid[r][c];\n }\n }\n\n return total_increase;\n}\n```\n```Ruby []\nclass Solution\n def max_increase_keeping_skyline(grid)\n n = grid.size\n\n # Find the maximum elements in each row and column\n row_max = grid.map { |row| row.max } # Efficiently find row max using map\n col_max = (0...n).map { |c| grid.map { |row| row[c] }.max } # Efficiently find col max using map\n\n # Calculate the total increase while maintaining the skyline\n total_increase = 0\n (0...n).each do |r|\n (0...n).each do |c|\n total_increase += [row_max[r], col_max[c]].min - grid[r][c]\n end\n end\n\n total_increase\n end\nend\n```\n# Don\'t Scroll BELOW(THANK YOU)\n.\n.\n.\n.\n.\n.\n.\n![image.png](https://assets.leetcode.com/users/images/fd24cc2a-08b4-42d1-a890-635bebdc9c64_1716975019.0761998.png)\n
12
0
['Array', 'Greedy', 'C', 'Matrix', 'Python', 'C++', 'Java', 'Python3', 'Ruby', 'JavaScript']
0
max-increase-to-keep-city-skyline
easiest solution || c++ || easy to understand || just simplest approach 🤔🤔
easiest-solution-c-easy-to-understand-ju-9i09
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
youdontknow001
NORMAL
2022-11-26T17:30:23.019243+00:00
2022-11-26T17:30:23.019285+00:00
885
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n = grid.size();\n // vector<vector<int>> row(n,vector<int>(n, 0)),col(n,vector<int>(n,0));\n vector<int> row,col;\n for(int i=0;i<n;i++){\n int maxi = INT_MIN;\n for(int j=0;j<n;j++){\n maxi=max(maxi,grid[i][j]);\n }\n row.push_back(maxi);\n }\n for(int i=0;i<n;i++){\n int maxi = INT_MIN;\n for(int j=0;j<n;j++){\n maxi=max(maxi,grid[j][i]);\n }\n col.push_back(maxi);\n }\n int sum = 0;\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n sum+=abs(grid[i][j]-min(row[i],col[j]));\n }\n }\n return sum;\n }\n};\n```
10
0
['C++']
1
max-increase-to-keep-city-skyline
Functional JavaScript
functional-javascript-by-chrisrocco-lmh8
```\ntranspose = m => m[0].map((x,i) => m.map(x => x[i]))\n\nvar maxIncreaseKeepingSkyline = function(grid) {\n let rowMaxes = grid.map( row => Math.max(...r
chrisrocco
NORMAL
2018-03-25T17:58:46.349499+00:00
2018-03-25T17:58:46.349499+00:00
1,228
false
```\ntranspose = m => m[0].map((x,i) => m.map(x => x[i]))\n\nvar maxIncreaseKeepingSkyline = function(grid) {\n let rowMaxes = grid.map( row => Math.max(...row))\n let colMaxes = transpose(grid).map( row => Math.max(...row))\n \n let increase = 0;\n for(let i = 0; i < grid.length; i++) {\n for(let j = 0; j < grid[i].length; j++){\n let newTotal = Math.min(rowMaxes[i], colMaxes[j])\n increase += newTotal - grid[i][j];\n }\n }\n return increase\n};
10
1
[]
4
max-increase-to-keep-city-skyline
Simple Python solution
simple-python-solution-by-cubicon-mkzn
\n def maxIncreaseKeepingSkyline(self, grid):\n rows_max = [0] * len(grid)\n cols_max = [0] * len(grid[0])\n\n for i in range(len(grid))
Cubicon
NORMAL
2018-03-25T03:01:37.963890+00:00
2018-09-19T23:10:33.725864+00:00
1,499
false
```\n def maxIncreaseKeepingSkyline(self, grid):\n rows_max = [0] * len(grid)\n cols_max = [0] * len(grid[0])\n\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n rows_max[i] = max(rows_max[i], grid[i][j])\n cols_max[j] = max(cols_max[j], grid[i][j])\n\n res = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n res += min(rows_max[i], cols_max[j]) - grid[i][j]\n\n return res\n```
10
0
[]
0
max-increase-to-keep-city-skyline
0ms JAVA | 98.98% faster & 100% memory
0ms-java-9898-faster-100-memory-by-onefi-r4u4
\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n if(grid == null)\n return 0;\n int n = grid.length;\n
onefineday01
NORMAL
2020-04-19T19:29:50.510992+00:00
2020-04-19T19:30:53.835828+00:00
1,595
false
```\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n if(grid == null)\n return 0;\n int n = grid.length;\n int m = grid[0].length;\n int maxrow[] = new int[n];\n int maxcol[] = new int[m];\n for(int i = 0; i < n; i++)\n for(int j = 0 ; j < m; j++){\n maxrow[i] = Math.max(maxrow[i], grid[i][j]);\n maxcol[j] = Math.max(maxcol[j], grid[i][j]);\n }\n int count = 0;\n for(int i = 0; i < n; i++)\n for(int j = 0 ; j < m; j++)\n count += (Math.min(maxrow[i], maxcol[j]) - grid[i][j]);\n \n return count;\n }\n}\n```
8
0
['Java']
1
max-increase-to-keep-city-skyline
C++, Straightforward O(m*n) time
c-straightforward-omn-time-by-ddev-53oh
int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n vector<int> row_max(grid.size(), INT_MIN);\n vector<int> col_max(grid.size() ? grid[0
ddev
NORMAL
2018-03-25T03:15:29.792564+00:00
2018-03-25T03:15:29.792564+00:00
2,211
false
int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n vector<int> row_max(grid.size(), INT_MIN);\n vector<int> col_max(grid.size() ? grid[0].size() : 0, INT_MIN);\n int result = 0;\n \n for(int i = 0 ; i < grid.size(); i++) {\n for(int j = 0; j < grid[0].size(); j++) {\n row_max[i] = max(row_max[i], grid[i][j]);\n col_max[i] = max(col_max[i], grid[j][i]);\n }\n }\n \n for(int i = 0 ; i < grid.size(); i++) {\n for(int j = 0; j < grid[0].size(); j++) {\n if(grid[i][j] < row_max[i] && grid[i][j] < col_max[j])\n result += min(row_max[i] - grid[i][j], col_max[j] - grid[i][j]);\n }\n }\n \n return result;\n }
7
1
[]
4
max-increase-to-keep-city-skyline
C++ simple solution 8 ms
c-simple-solution-8-ms-by-oleksam-o37p
\n// Please, UpVote, if you like it :-)\nint maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n\tint maxIncrease = 0, rows = grid.size(), cols = grid[0].s
oleksam
NORMAL
2021-01-24T17:15:56.033071+00:00
2021-01-24T17:22:04.667655+00:00
606
false
```\n// Please, UpVote, if you like it :-)\nint maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n\tint maxIncrease = 0, rows = grid.size(), cols = grid[0].size();\n\tvector<int> rowMax(rows, 0);\n\tvector<int> colsMax(cols, 0);\n\tfor (int i = 0; i < rows; i++) {\n\t\tfor (int j = 0; j < cols; j++) {\n\t\t\trowMax[i] = max(rowMax[i], grid[i][j]);\n\t\t\tcolsMax[j] = max(colsMax[j], grid[i][j]);\n\t\t}\n\t}\n\n\tint maxResult = 0;\n\tfor (int i = 0; i < rows; i++)\n\t\tfor (int j = 0; j < cols; j++)\n\t\t\tmaxResult += (min(rowMax[i], colsMax[j]) - grid[i][j]);\n\n\treturn maxResult;\n}\n```\n
6
1
['C', 'C++']
0
max-increase-to-keep-city-skyline
48ms Python3 solution
48ms-python3-solution-by-vanden-qn28
To my surprise (I am not a speed demon), this was deemed faster than 100% of Py3 submissions:\n\nclass Solution:\n def maxIncreaseKeepingSkyline(self, grid):
vanden
NORMAL
2018-04-23T18:15:30.721671+00:00
2018-08-13T19:15:14.368004+00:00
2,166
false
To my surprise (I am not a speed demon), this was deemed faster than 100% of Py3 submissions:\n```\nclass Solution:\n def maxIncreaseKeepingSkyline(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n """\n row_maxes = [max(row) for row in grid]\n\n col_maxes = []\n for colIdx in range(len(grid[0])):\n col = [grid[row][colIdx] for row in range(len(grid))]\n col_maxes.append(max(col))\n\n increases = 0\n for idx, row in enumerate(grid):\n for jdx, height in enumerate(row):\n increases += min(row_maxes[idx], col_maxes[jdx]) - height\n return increases\n```
6
0
[]
3
max-increase-to-keep-city-skyline
Concise Python Solution
concise-python-solution-by-szhi-dx4j
``` \n\t\tlenth = len(grid)\n hhigh = [max(row) for row in grid]\n vhigh = [max(col) for col in zip(*grid)]\n ans = 0\n for i
szhi
NORMAL
2019-08-27T19:52:28.679606+00:00
2019-08-27T19:52:28.679640+00:00
386
false
``` \n\t\tlenth = len(grid)\n hhigh = [max(row) for row in grid]\n vhigh = [max(col) for col in zip(*grid)]\n ans = 0\n for i in range(lenth):\n for j in range(lenth):\n ans+=(min(hhigh[i],vhigh[j]) - grid[i][j])\n return(ans)\n
5
0
[]
0
max-increase-to-keep-city-skyline
Beats 100% and easy to understand...
beats-100-and-easy-to-understand-by-krus-vwmi
Intuition : Calculate Row max and Column max, compare.\n Describe your first thoughts on how to solve this problem. \n\n# Approach : Row max & Column max.\n Des
Krushna_Yeshwante
NORMAL
2024-09-18T13:09:33.858076+00:00
2024-09-18T13:09:33.858106+00:00
190
false
# Intuition : Calculate Row max and Column max, compare.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach : Row max & Column max.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity : O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity : O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int n = grid.length, sum=0;\n int rMax[] = new int[n];\n int cMax[] = new int[n];\n for(int i=0; i<n; i++){\n int row=0, col=0;\n for(int j=0; j<n; j++){\n row=Math.max(row, grid[i][j]);\n col=Math.max(col, grid[j][i]);\n rMax[i]=row;\n cMax[i]=col;\n }\n }\n for(int i=0; i<n; i++){\n for(int j=0; j<n; j++){\n sum+=(Math.min(rMax[i], cMax[j]) - grid[i][j]);\n }\n }\n return sum;\n }\n}\n```
4
0
['Array', 'Greedy', 'Matrix', 'Java']
0
max-increase-to-keep-city-skyline
easy C++ solution,98% time 80% memory
easy-c-solution98-time-80-memory-by-shub-lcrv
Intuition\nstore each row max element a "rowmax" vector and each column max element in "colmax" vector;\n Describe your first thoughts on how to solve this prob
shubhamo7
NORMAL
2023-04-28T14:02:42.887662+00:00
2023-04-28T14:02:42.887690+00:00
419
false
# Intuition\nstore each row max element a "rowmax" vector and each column max element in "colmax" vector;\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n-> create two vectors to store each row max element and each column max element.\n-> store max element of row 0 in 0th index of "rowmax" vector.\n-> store max element of col 0 in 0th index of "colmax" vector.\n-> after storing we just has to compare the minimum of (current element -( rowmax of that row ,colmax of that column)).\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N*N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N*N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n <!-- create two vectors to store each row max element and each column max element. -->\n vector<int> rowmax;\n vector<int> colmax;\n int rmx;\n int cmx;\n int n = grid.size();\n for(int i = 0;i<n;i++){\n rmx = INT_MIN;\n cmx = INT_MIN;\n for(int j = 0;j<n;j++){\n <!-- store max element of row 0 in 0th index of "rowmax" vector. -->\n if(grid[i][j]>rmx) rmx = grid[i][j];\n <!-- store max element of col 0 in 0th index of "colmax" vector. -->\n if(grid[j][i]>cmx) cmx = grid[j][i];\n }\n rowmax.push_back(rmx);\n colmax.push_back(cmx);\n }\n\n int count =0;\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n <!-- after storing we just has to compare the minimum of (current element -( rowmax of that row ,colmax of that column)). -->\n count += min(abs(grid[i][j]-rowmax[i]),abs(grid[i][j]-colmax[j]));\n }\n }\n return count;\n }\n};\n```
4
0
['C++']
0
max-increase-to-keep-city-skyline
✅ JavaScript - explanation
javascript-explanation-by-daria_abdulnas-tlpv
Approach\n Describe your approach to solving the problem. \nAt first, we count the maximum height of buildings in rows and columns, keep it in rMax and cMax. Yo
daria_abdulnasyrova
NORMAL
2023-03-28T07:21:08.179370+00:00
2023-03-29T08:12:11.967371+00:00
173
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nAt first, we count the maximum height of buildings in rows and columns, keep it in `rMax` and `cMax`. You can imagine that `rMax` is a city\'s skyline if you look at the city from East or West (they are the same as it is projection) and `cMax` is a city\'s skyline if you look at the city from North or South.\nThen you need to decide for each building what amount the height can be increased by without changing the city\'s skyline, it means not to overheight the maximum buiding in a row or in a column, so we need to get minimum of `rMax` and `cMax` for each row and column and find the difference with current height of building. \n\n# Code\n```\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar maxIncreaseKeepingSkyline = function(grid) {\n let result = 0, n = grid.length;\n let rMax = new Array(grid.length).fill(0);\n let cMax = new Array(grid.length).fill(0);\n\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n rMax[i] = Math.max(rMax[i], grid[i][j]);\n cMax[j] = Math.max(cMax[j], grid[i][j]);\n }\n }\n\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n result += Math.min(rMax[i], cMax[j]) - grid[i][j];\n }\n }\n\n return result;\n};\n```
4
0
['JavaScript']
0
max-increase-to-keep-city-skyline
Easy c++ solution with explanation.
easy-c-solution-with-explanation-by-luff-gb79
Intuition\nHeight of any building can only be raised to the of the maximum height building in the same column and same row as aforementioned building.\n\n# Appr
luffy0908
NORMAL
2023-03-24T16:21:46.902087+00:00
2023-03-24T16:21:46.902179+00:00
790
false
# Intuition\nHeight of any building can only be raised to the of the maximum height building in the same column and same row as aforementioned building.\n\n# Approach\nMake 2 vectors where you can store the maximum height in a given row and column. Since we are asked not to change the skyline from any cardinal direction we can only raise height of the building by minimum of maximum heights in the row and column of the said building.\n`Note : Skyline would be same when viewed from south and north. Its same for east and west.`\n\n# Complexity\n- Time complexity:\nO(N*N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n = grid.size();\n vector<int>rowmax(n,0);\n vector<int>colmax(n,0);\n int sum = 0;\n for( int i = 0; i < n; i++ ){\n for( int j = 0; j < n; j++ ){\n rowmax[i] = max(rowmax[i],grid[i][j]);\n colmax[j] = max(colmax[j],grid[i][j]);\n }\n }\n for( int i = 0; i < n; i++ ){\n for( int j = 0; j < n; j++ ){\n if( grid[i][j] <= min(rowmax[i],colmax[j]) ){\n sum += min(rowmax[i],colmax[j]) - grid[i][j];\n }\n }\n }\n\n return sum;\n }\n};\n```
4
0
['C++']
0
max-increase-to-keep-city-skyline
Solution in C++
solution-in-c-by-ashish_madhup-fa38
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
ashish_madhup
NORMAL
2023-02-25T10:34:42.863269+00:00
2023-02-25T10:34:42.863317+00:00
548
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n = grid.size(), ans = 0;\n vector<pair<int,int>> v(n,{-1,-1});\n for(int i=0; i<n; ++i){\n for(int j=0; j<n; ++j){\n v[i].first = max(v[i].first,grid[i][j]);\n v[j].second = max(v[j].second,grid[i][j]);\n }\n }\n for(int i=0,k=0; i<n; ++i,++k){\n for(int j=0; j<n; ++j)\n ans += min(v[i].first,v[j].second) - grid[i][j];\n }\n return ans;\n }\n};\n```
4
0
['C++']
1
max-increase-to-keep-city-skyline
[PYTHON 3] EASY | SIMPLE SOLUTION | STRAIGHT FORWARD
python-3-easy-simple-solution-straight-f-uaa2
```\nclass Solution:\n def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:\n rows_max = [0] * len(grid)\n cols_max = [0] * len(g
omkarxpatel
NORMAL
2022-07-12T00:55:40.562554+00:00
2022-07-12T00:55:40.562594+00:00
1,148
false
```\nclass Solution:\n def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:\n rows_max = [0] * len(grid)\n cols_max = [0] * len(grid[0])\n\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n rows_max[i] = max(rows_max[i], grid[i][j])\n cols_max[j] = max(cols_max[j], grid[i][j])\n\n res = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n res += min(rows_max[i], cols_max[j]) - grid[i][j]\n\n return res
4
0
['Python', 'Python3']
0
max-increase-to-keep-city-skyline
🥟 C++ || EASY SOL WITH YT LINK EXPLANATION
c-easy-sol-with-yt-link-explanation-by-v-b7xk
\n\n\t\tclass Solution {\n\t\tpublic:\n\t\t\tint maxIncreaseKeepingSkyline(vector>& grid) {\n\t\t\t\tint n = grid.size(), ans = 0;\n\t\t\t\tvector rows(n);\n\t\
venom-xd
NORMAL
2022-04-21T16:38:15.216405+00:00
2022-04-21T16:38:15.216448+00:00
420
false
\n\n\t\tclass Solution {\n\t\tpublic:\n\t\t\tint maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n\t\t\t\tint n = grid.size(), ans = 0;\n\t\t\t\tvector<int> rows(n);\n\t\t\t\tvector<int> cols(n);\n\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\t\t\trows[i] = max(rows[i], grid[i][j]);\n\t\t\t\t\t\t//cout<<rows[i] = max(rows[i], grid[i][j]);\n\t\t\t\t\t\t//8,7,9,3\n\t\t\t\t\t\tcols[j] = max(cols[j], grid[i][j]);\n\t\t\t\t\t\t//cout<<cols[j] = max(cols[j], grid[i][j]);\n\t\t\t\t\t\t//9,4,8,7\n\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\t\t\tans += min(rows[i], cols[j]) - grid[i][j];\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn ans;\n\t\t\t}\n\t\t};\n\t\t\nhttps://www.youtube.com/watch?v=tHu9bndGNmA (Logic from this video)
4
0
['C', 'C++']
0
max-increase-to-keep-city-skyline
Python | Easy | Straight Forward | Easy to Understand
python-easy-straight-forward-easy-to-und-idbn
Code\n\nclass Solution:\n def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:\n # get list of columns by transposing the matrix \n
RahulAnand28
NORMAL
2023-10-15T07:29:52.647136+00:00
2023-10-15T07:29:52.647153+00:00
86
false
# Code\n```\nclass Solution:\n def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:\n # get list of columns by transposing the matrix \n col_lst = [list(col) for col in zip(*grid)]\n col_max = [max(i) for i in col_lst]\n row_max = [max(i) for i in grid]\n final_num = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n final_num += min(row_max[i], col_max[j]) - grid[i][j]\n return final_num\n \n```
3
0
['Python3']
0
max-increase-to-keep-city-skyline
Easiest C++
easiest-c-by-sparrow_harsh-q6h9
Intuition\nWe can increase height of a cell to min(maximum of row, maximum of column).\n\n# Approach\nWe will find maximumn elements of all the rows and all the
sparrow_harsh
NORMAL
2023-06-07T06:49:38.600951+00:00
2023-06-07T06:49:38.600999+00:00
298
false
# Intuition\nWe can increase height of a cell to min(maximum of row, maximum of column).\n\n# Approach\nWe will find maximumn elements of all the rows and all the columns and store it into a vector.\n\nThen we will traverse through grid and find minimum of row and col say te. And then we will add abs(te- grid[i][j]) to answer.\n\n# Complexity\n- Time complexity:\nO(n*n)\n\n\n# Code\n```\nclass Solution {\npublic:\n \n /* we can icrease height of a cell with min(max(row),max(coln)) */\n\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n=grid.size();\n\n vector<int> row(n),coln(n);\n \n /* Finding max of all row element */\n for(int i=0;i<n;i+=1){\n int mx=0;\n for(int j=0;j<n;j+=1){\n mx= max(grid[i][j],mx);\n }\n row[i]=mx;\n }\n\n /* Finding max of all column element */\n for(int j=0;j<n;j+=1){\n int mx=0;\n for(int i=0;i<n;i+=1){\n mx= max(grid[i][j],mx);\n }\n coln[j]=mx;\n }\n\n int ans=0;\n for(int i=0;i<n;i+=1){\n for(int j=0;j<n;j+=1){\n int te= min(row[i],coln[j]);\n ans+= abs(te-grid[i][j]);\n }\n }\n return ans;\n }\n};\n```\nPLEASEEE UPVOTEE IF IT HELPED
3
0
['Greedy', 'C++']
0
max-increase-to-keep-city-skyline
Easy python 5 liner solution solution 🔥🔥🔥🔥
easy-python-5-liner-solution-solution-by-yfut
\n# Code\n\nclass Solution(object):\n def maxIncreaseKeepingSkyline(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n
Lalithkiran
NORMAL
2023-03-19T05:28:13.776584+00:00
2023-03-19T05:28:13.776634+00:00
476
false
![image.png](https://assets.leetcode.com/users/images/ab92f6d7-836f-41a7-a237-418dbb5728da_1679203597.9839773.png)\n# Code\n```\nclass Solution(object):\n def maxIncreaseKeepingSkyline(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n """\n sm=0\n lst=[max(i) for i in zip(*grid)]\n lst1=[max(i) for i in grid]\n for i in range(len(grid)):\n for j in range(len(grid)):\n sm+=min(lst[j],lst1[i])-grid[i][j]\n return sm\n```
3
0
['Array', 'Greedy', 'Matrix', 'Python']
0
max-increase-to-keep-city-skyline
Java Solution, beats 100%
java-solution-beats-100-by-theycallmepre-4bzc
Intuition\nContours are decided by the maximum heights, for north and south watchers, the buildings with max heights in each column and for east and west watche
TheyCallMePrem
NORMAL
2023-01-08T18:31:53.926356+00:00
2023-01-08T18:31:53.926391+00:00
1,166
false
# Intuition\nContours are decided by the maximum heights, for north and south watchers, the buildings with max heights in each column and for east and west watchers, max heights in each row. \n\n# Approach\nIterate over grid[][] to find maximum elements of each row and each column, the any element in updated grid[][], say grid[i][j] will be equal to Min(rowMax[i], colMax[j]). Calculate the difference this way.\n\n# Complexity\n- Time complexity:\nO(n^2) [nested for loop]\n\n- Space complexity:\nO(n^2) [2-d array]\n\n# Code\n```\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int n = grid.length;\n int [] rowMax = new int[n];\n int [] colMax = new int[n];\n\n for(int i=0;i<n;i++){\n rowMax[i]=grid[i][0];\n colMax[i]=grid[0][i];\n for(int j=0; j<n; j++){\n rowMax[i]=Math.max(rowMax[i], grid[i][j]); \n colMax[i]= Math.max(colMax[i], grid[j][i]);\n }\n \n }\n // for(int i=0;i<n;i++){\n // System.out.print(rowMax[i]);\n // // System.out.println(colMax[i]);\n // }\n // System.out.print("------------");\n // for(int i=0;i<n;i++){\n // // System.out.println(rowMax[i]);\n \n // System.out.print(colMax[i]);\n // }\n\n int sum=0;\n for(int i=0;i<n;i++){\n for(int j=0; j<n; j++){\n sum+=Math.min(rowMax[i], colMax[j])-grid[i][j];\n }\n }\n return sum;\n }\n}\n```
3
0
['Java']
3
max-increase-to-keep-city-skyline
Detailed Explanation || CPP || DP
detailed-explanation-cpp-dp-by-sansk_rit-px6q
Intuition\nBy looking at the problem, we understand that the tallest building in that row from that direction is the one contributing to the skyline of that dir
Sansk_Ritu
NORMAL
2022-12-24T12:26:57.120274+00:00
2022-12-24T12:26:57.120302+00:00
100
false
# Intuition\nBy looking at the problem, we understand that the tallest building in that row from that direction is the one contributing to the skyline of that direction\nSuppose you are looking from the bottom (South) then for the grid[0][j]] the tallest building in jth column will be considered for answer\n\n# Approach\nHere we can solve this problem by storing the height of tallest building from each direction ( basically either of the two sets with 90 degrees of difference north-east || west-south )\nAnd then we shall calculate the additional height that can be added without changing the maximum value for that row and column\n\n# Complexity\n- Time complexity:\n O(n*m)\n\n- Space complexity:\n O(n+m)\n\n# Code\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n vector<int> row (n, 0);\n vector<int> col (m, 0);\n int ans = 0;\n for (int i=0; i<n; i++){\n for (int j=0; j<m; j++){\n ans = max ( ans, grid[i][j] );\n col[j] = max (col[j], grid[i][j]);\n }\n row[i]=ans;\n ans=0;\n }\n ans = 0;\n for (int i=0; i<n; i++){\n for (int j=0; j<m; j++){\n int k = min ( row[i], col[j] );\n int diff = k - grid[i][j] ;\n cout<<k<<" ";\n if (diff>0){\n ans += diff;\n }\n }\n }\n return ans;\n }\n};\n```
3
0
['Hash Table', 'Dynamic Programming', 'Greedy', 'C++']
0
max-increase-to-keep-city-skyline
Java Easy and fast
java-easy-and-fast-by-htksaurav-uufo
\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int []row = new int[grid.length];\n int []column = new int[grid[0].
htksaurav
NORMAL
2022-03-29T17:14:39.852408+00:00
2022-03-29T17:14:39.852488+00:00
351
false
```\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int []row = new int[grid.length];\n int []column = new int[grid[0].length];\n \n for(int i=0;i<grid.length;i++){\n int maxRow = 0;\n int maxColumn = 0;\n for(int j=0;j<grid[i].length;j++){\n if(grid[i][j]>maxRow)\n maxRow = grid[i][j];\n if(grid[j][i]>maxColumn)\n maxColumn = grid[j][i];\n }\n row[i]=maxRow;\n column[i]=maxColumn;\n }\n int sum = 0;\n for(int i=0;i<row.length;i++){\n for(int j=0;j<column.length;j++){\n sum += Math.min(row[i], column[j])-grid[i][j];\n }\n }\n return sum;\n }\n}\n```
3
0
['Java']
0
max-increase-to-keep-city-skyline
[Python3] max per row & column
python3-max-per-row-column-by-ye15-l3j6
Algo \nThe maximum increase in height at i, j is the difference between the minimum of max of row i and max of col j and grid[i][j]. \n\nImplementation \n\nclas
ye15
NORMAL
2020-11-12T03:50:37.454831+00:00
2020-11-12T03:50:37.454876+00:00
329
false
Algo \nThe maximum increase in height at `i, j` is the difference between the minimum of max of row `i` and max of col `j` and `grid[i][j]`. \n\nImplementation \n```\nclass Solution:\n def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n row = [max(x) for x in grid]\n col = [max(x) for x in zip(*grid)]\n ans = 0 \n for i in range(m):\n for j in range(n): \n ans += min(row[i], col[j]) - grid[i][j]\n return ans \n```\n\nAnalysis \nTime complexity `O(MN)`\nSpace complexity `O(M+N)`
3
0
['Python3']
0
max-increase-to-keep-city-skyline
Clear, Understandable Solution using Map and Meaningful Variables (~90% Speed, 50% Memory) O(n^2)
clear-understandable-solution-using-map-3k8id
```\n/*\nTo maximize the height while maintaining the height of the skyline from the view of the top/botttom and right/left:\n GOAL: At every A[row][col] we
masterofnone
NORMAL
2019-11-11T14:43:08.678852+00:00
2019-11-11T17:30:13.122431+00:00
559
false
```\n/**\nTo maximize the height while maintaining the height of the skyline from the view of the top/botttom and right/left:\n GOAL: At every A[row][col] we need to find the max of that row, column, and then make the current A[i][j] = the minimum of the two, as long as it\'s greater than the current value\n 1) Make a nested for loop to go though each value and find the max col and rows\n - We will store this in a map/object for fast access.\n 2) Go though the whole 2D array, find the Min(max of that col, max of that row) and replace the current Array[row][col]!\n 3) Pet a dog for happiness \n*/\nvar maxIncreaseKeepingSkyline = function(grid) {\n let rowM = {} //Map for the rows max\n let colsM = {} //Map for the columns max\n let sum = 0 // Total height we can add\n \n //findMaxRowsCols will go though each row and col and populate the max of each row\n // and colum in a key: value way.\n //From the example, after this function runs the map looks like:\n //console.log(rowM) => { \'0\': 8, \'1\': 7, \'2\': 9, \'3\': 3 }\n //console.log(colsM)=> { \'0\': 9, \'1\': 4, \'2\': 8, \'3\': 7 }\n findMaxRowsCols(grid, rowM, colsM)\n \n //Now that we have the max of a given row and column, let\'s see how much we can replace each cell by\n for(let row = 0; row < grid.length; row ++){\n for(let col = 0; col < grid[0].length; col ++){\n //The new height should be the MIN of the max of a given row and column (so we dont ruine the skyline;)\n let newH = Math.min(rowM[row], colsM[col])\n //If the current height is smaller do the replacement and count! (saves us some uneeded work)\n if(grid[row][col] < newH){\n sum += newH -grid[row][col]\n grid[row][col] = newH\n }\n }\n }\n return sum\n};\n\n\nvar findMaxRowsCols = function(grid, rowM, colsM){\n //Find the max of each row\n for(let row = 0; row < grid.length; row ++){\n let max = 0\n for(let curr = 0; curr < grid[0].length; curr ++){\n if(grid[row][curr] > max){\n max = grid[row][curr] \n }\n rowM[row] = max\n }\n }\n \n //Find the max for each column\n for(let col = 0; col < grid.length; col ++){\n let max = 0\n for(let curr = 0; curr < grid.length; curr ++){\n if(grid[curr][col] > max){\n max = grid[curr][col]\n }\n colsM[col] = max\n }\n }\n \n}\n};
3
0
['JavaScript']
0
max-increase-to-keep-city-skyline
Done but I need to understand the problem ka description 😅 :D
done-but-i-need-to-understand-the-proble-k3or
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
yesyesem
NORMAL
2024-10-12T18:49:57.014766+00:00
2024-10-12T18:49:57.014790+00:00
91
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n \n int rows=grid.size();\n int cols=grid[0].size();\n vector<int>rowmax(rows);\n vector<int>colmax(cols);\n\n int maxr;\n int maxc;\n for(int i=0;i<rows;i++)\n {\n maxr=*max_element(grid[i].begin(),grid[i].end());\n rowmax[i]=maxr;\n \n }\n\n // for(int i=0;i<rows;i++)\n // cout<<rowmax[i]<<" ";\n \n for(int i=0;i<rows;i++)\n { maxc=0;\n for(int j=0;j<cols;j++)\n {\n if(grid[j][i]>maxc) \n maxc=grid[j][i];\n }\n\n colmax[i]=maxc;\n }\n\n // for(int i=0;i<rows;i++)\n // cout<<colmax[i]<<" ";\n\n int c=0;\n\n for(int i=0;i<rows;i++)\n {\n for(int j=0;j<cols;j++)\n {\n c+=min(rowmax[i],colmax[j])-grid[i][j];\n }\n }\n \n \n return c;\n \n }\n};\n```
2
0
['C++']
0
max-increase-to-keep-city-skyline
Beats 100% and easy to understand...
beats-100-and-easy-to-understand-by-anik-qamb
Intuition : Calculate Row max and Column max, compare.\n Describe your first thoughts on how to solve this problem. \n\n# Approach : Row max & Column max.\n Des
Aniket16903
NORMAL
2024-09-18T13:09:30.402540+00:00
2024-09-18T13:09:30.402573+00:00
46
false
# Intuition : Calculate Row max and Column max, compare.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach : Row max & Column max.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity : O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity : O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int n = grid.length, sum=0;\n int rMax[] = new int[n];\n int cMax[] = new int[n];\n for(int i=0; i<n; i++){\n int row=0, col=0;\n for(int j=0; j<n; j++){\n row=Math.max(row, grid[i][j]);\n col=Math.max(col, grid[j][i]);\n rMax[i]=row;\n cMax[i]=col;\n }\n }\n for(int i=0; i<n; i++){\n for(int j=0; j<n; j++){\n sum+=(Math.min(rMax[i], cMax[j]) - grid[i][j]);\n }\n }\n return sum;\n }\n}\n```
2
0
['Array', 'Greedy', 'Matrix', 'Java']
0
max-increase-to-keep-city-skyline
Best Java Solution || Beats 100%
best-java-solution-beats-100-by-ravikuma-clz2
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
ravikumar50
NORMAL
2023-09-10T09:23:11.268816+00:00
2023-09-10T09:23:11.268833+00:00
135
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] arr) {\n\n int n = arr.length;\n int m = arr[0].length;\n int row[] = new int[n];\n int col[] = new int[m];\n\n for(int i=0; i<n; i++){\n int max = Integer.MIN_VALUE;\n for(int j=0; j<m; j++){\n max = Math.max(arr[i][j],max);\n }\n row[i] = max;\n }\n\n \n for(int j=0; j<m; j++){\n int max = Integer.MIN_VALUE;\n for(int i=0; i<n; i++){\n max = Math.max(arr[i][j],max);\n }\n col[j] = max;\n }\n\n int ans = 0;\n\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n int max = Math.min(row[i],col[j]);\n if(arr[i][j]<max) ans = ans+max-arr[i][j];\n }\n }\n return ans;\n }\n}\n```
2
0
['Java']
0
max-increase-to-keep-city-skyline
python3 solution using 2 arrays beats 98% O(N) space
python3-solution-using-2-arrays-beats-98-lbgj
Intuition\n Describe your first thoughts on how to solve this problem. \nhere a contains maximum in each row\nhere b cointains maximum in each column\nc has max
Sumukha_g
NORMAL
2023-08-03T13:34:38.550945+00:00
2023-08-03T13:34:38.550979+00:00
421
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nhere a contains maximum in each row\nhere b cointains maximum in each column\nc has max in each column which will be appendded to b\nafter having these we just just need to compare a[i] and b[j] whichever is lower to maintain skyline and then we can just subtract element from the minimum value \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n**0(N^2)**\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n**O(N)**\n# Code\n```\nclass Solution:\n def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:\n a=[max(i) for i in grid]\n b=[]\n l=len(grid)\n for i in range(l):\n "list comprehension for column"\n c=max([j[i] for j in grid])\n b.append(c)\n ans=0\n for i in range(l):\n for j in range(l):\n "can also have varible m storing min a[i] and b[j]"\n ans+=min(a[i],b[j])-grid[i][j]\n return ans\n```
2
0
['Array', 'Matrix', 'Python3']
0
max-increase-to-keep-city-skyline
Simple C++ Solution | Intuitive | Beginner-Friendly Explanation
simple-c-solution-intuitive-beginner-fri-ix10
Intuition\nThe primary thing to understand here is that we do not need to take all four points of view into consideration. If you observe carefully, the skyline
Anuvab
NORMAL
2023-08-02T19:52:50.859778+00:00
2023-08-12T06:14:04.797707+00:00
23
false
# Intuition\nThe primary thing to understand here is that we do not need to take all four points of view into consideration. If you observe carefully, the skyline view from the $$North(N)$$ side and the skyline view from the $$South(S)$$ side are simply reversed because it is the same skyline. It is like the viewing the same building from the front and then from behind. The same logic works for $$East(E)$$ and $$West(W)$$. \n\nNow, lets try and understand exactly what the $$Skyline$$ is.\n\nThe skyline is basically the *silhouette of the tallest building in the column from the side where we are viewing it*. Therefore, it is clear that the skyline is only affected by the height of the tallest building in that column. Thus, we can safely increase the heights of all the other buildings (smaller than the tallest building) to the height of the tallest building without affecting the skyline in any way. However, in doing so, we might end up changing the skyline in the perpendicular direction, i.e. the skyline for that row.\n\nTo keep the skyline same from both directions, we simply have to increase every building height at cell $$(i,j)$$ to the **minimum height of the tallest buildings** in the $$ith$$ row and the $$jth$$ column.\n\n# Approach\nTo avoid calculating the mximum height in each row and each column at every step, I have used 2 vectors `maxHeightRow` and `maxHeightColumn` to store the maximum heights in each row and column separately.\nAfter that, I have simply traversed the entire matrix and found the maximum increment possible and added it to the result.\n```\nincrease+=(min(maxHeightRow[i],maxHeightColumn[j])-grid[i][j]);\n```\nThe Approach has also been throughly elucidated in the comments below. \n\n\n# Code\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n // person viewing from north sees the reverse of the one viewing from south\n // similarly for east and west\n // to keep skyline same in either N-S way or E-W way,\n // we can increase all building heights in that row/col to the max. in that row/col\n // to keep both directions unaffected,\n // we have to find out the minimum of max. heights in both the directions\n // to reduce time, we have to keep the max. height in row and col stored in 2 vectors\n int m=grid.size(),n=grid[0].size(),increase=0;\n vector<int> maxHeightRow,maxHeightColumn;\n // to find out the max. height in each row\n for(vector<int> row:grid) maxHeightRow.push_back(*max_element(row.begin(),row.end()));\n // to find out the maximum height in each column\n for(int i=0;i<n;i++){\n int maxHt=INT_MIN;\n for(int j=0;j<m;j++) maxHt=max(maxHt,grid[j][i]);\n maxHeightColumn.push_back(maxHt);\n }\n // to calculate the total increment needed in heights\n for(int i=0;i<m;i++)\n for(int j=0;j<n;j++) \n increase+=(min(maxHeightRow[i],maxHeightColumn[j])-grid[i][j]);\n return increase;\n }\n};\n```
2
0
['Array', 'Matrix', 'C++']
0
max-increase-to-keep-city-skyline
✅Easy C++ code using for loop || BEGINNER FRIENDLY
easy-c-code-using-for-loop-beginner-frie-vdis
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
vishu_0123
NORMAL
2023-02-26T09:33:44.589219+00:00
2023-02-26T09:38:46.677231+00:00
238
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n vector<vector<int>> cpy,transpose;\n cpy=grid;\n transpose=grid;\n int n=grid.size();\n for(int i=0;i<n;i++){\n int a= *max_element(grid[i].begin(),grid[i].end());\n for(int j=0;j<n;j++){\n cpy[i][j]=a;\n }\n }\n \n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n transpose[j][i]=grid[i][j];\n\n }\n }\n for(int i=0;i<n;i++){\n int b=*max_element(transpose[i].begin(),transpose[i].end());\n for(int j=0;j<n;j++){\n if(b<cpy[j][i]){\n cpy[j][i]=b;\n }\n }\n }\n \n int ans=0;\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n ans+=(cpy[i][j]-grid[i][j]);\n }\n }\n return ans;\n }\n};\nDo UPVOTE if you like\n```
2
0
['C++']
0
max-increase-to-keep-city-skyline
CPP SOLUTION || EASY TO UNDERSTAND || SIMPLE AND CLEAN CODE
cpp-solution-easy-to-understand-simple-a-dft5
\n\n# Code\n\nclass Solution {\n int n;\n int skyline(vector<vector<int>>& v,int r,int c){\n int h1 = -1e9,h2=-1e9;\n for(int i =0;i<n;++i){
msdarshan
NORMAL
2023-02-13T17:58:01.893115+00:00
2023-02-13T17:58:01.893160+00:00
28
false
\n\n# Code\n```\nclass Solution {\n int n;\n int skyline(vector<vector<int>>& v,int r,int c){\n int h1 = -1e9,h2=-1e9;\n for(int i =0;i<n;++i){\n h1 = max(h1,v[r][i]);\n h2 = max(h2,v[i][c]);\n }\n return min(h1,h2);\n }\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int ans=0;\n n = grid.size();\n\n vector<vector<int>> h(n,vector<int>(n,0));\n for(int i=0;i<n;++i){\n for(int j=0;j<n;++j){\n h[i][j] = skyline(grid,i,j);\n }\n }\n for(int i=0;i<n;++i){\n for(int j=0;j<n;++j){\n ans+=h[i][j]-grid[i][j];\n }\n }\n\n return ans;\n }\n};\n```
2
0
['C++']
0
max-increase-to-keep-city-skyline
📌 c++ solution | store max from left view and top view ✔
c-solution-store-max-from-left-view-and-yq5mu
\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n vector<int> top, left;\n int ln= grid.size();\n
1911Uttam
NORMAL
2023-02-10T13:36:06.106039+00:00
2023-02-10T13:36:06.106094+00:00
249
false
```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n vector<int> top, left;\n int ln= grid.size();\n \n for(auto &x:grid){\n left.push_back(*max_element(x.begin(), x.begin()+ln));\n }\n \n for(int j=0;j<ln;j++){\n int m= 0;\n for(int i=0;i<ln;i++) m= max(m,grid[i][j]);\n \n top.push_back(m);\n }\n \n int ans=0;\n for(int i=0;i<ln;i++){\n for(int j=0;j<ln;j++){\n if(grid[i][j]==left[i] || grid[i][j]== top[j]) continue;\n \n ans+= abs(min(left[i], top[j])- grid[i][j]);\n }\n }\n \n return ans;\n }\n};\n```
2
0
['C', 'C++']
0
max-increase-to-keep-city-skyline
Easy C++ traversal O(NxN) solution
easy-c-traversal-onxn-solution-by-shrist-mwi3
\n# Code\n\nclass Solution {\npublic:\n int findMax(vector<int>arr){\n int maxi=arr[0];\n for(int i=1;i<arr.size();i++){\n if(arr[i]
Shristha
NORMAL
2023-01-11T13:00:22.075531+00:00
2023-01-11T13:00:22.075577+00:00
690
false
\n# Code\n```\nclass Solution {\npublic:\n int findMax(vector<int>arr){\n int maxi=arr[0];\n for(int i=1;i<arr.size();i++){\n if(arr[i]>maxi){\n maxi=arr[i];\n }\n }\n return maxi;\n }\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n unordered_map<int,int>m;//stores maximum height in each col & row\n int n=grid.size();\n //find max in each row\n for(int i=0;i<n;i++){\n int temp=findMax(grid[i]);\n m[i]=temp;\n }\n for(int i=0;i<n;i++){\n for(int j=i+1;j<n;j++){\n swap(grid[i][j],grid[j][i]);\n }\n }\n //max in each col\n for(int i=0;i<n;i++){\n int temp=findMax(grid[i]);\n m[i+n]=temp;\n }\n int res=0;\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n res+=(min(m[i],m[j+n])-grid[i][j]);\n }\n }\n return res;\n\n \n }\n};\n```
2
0
['C++']
0
max-increase-to-keep-city-skyline
0ms beats 100% Super readable code with comments
0ms-beats-100-super-readable-code-with-c-wqyl
Intuition\n Describe your first thoughts on how to solve this problem. \nThis shit is super difficult i will never be able to solve this but i\'ll try anyways.\
tdf56f756bg56r8iohgwexu
NORMAL
2023-01-03T01:34:50.340161+00:00
2023-01-03T01:34:50.340196+00:00
645
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis shit is super difficult i will never be able to solve this but i\'ll try anyways.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nA skyline is defined by the highest buildings in a collumn or row.\n\nIf i keep track of the tallest buildings i will know the highest height i can increase buildings to.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nimpl Solution {\n pub fn max_increase_keeping_skyline(grid: Vec<Vec<i32>>) -> i32 {\n \n let mut vertical: Vec<i32> = vec![0;grid.len()];\n let mut horizontal: Vec<i32> = vec![0;grid.len()];\n\n //Find highest buildings\n for row in 0..grid.len(){\n for collumn in 0..grid.len(){\n horizontal[row] = horizontal[row].max(grid[row][collumn]);\n vertical[collumn] = vertical[collumn].max(grid[row][collumn]); \n }\n }\n \n //Result value\n let mut res:i32 = 0;\n\n //Find buildings that we can increase\n for row in 0..grid.len(){\n for collumn in 0..grid.len(){\n if grid[row][collumn] < horizontal[row] \n && grid[row][collumn] < vertical[collumn] {\n res += (horizontal[row].min(vertical[collumn]) - grid[row][collumn]);\n }\n }\n }\n res\n }\n}\n```
2
0
['Rust']
0
max-increase-to-keep-city-skyline
Easy Java Solution
easy-java-solution-by-mandarin_075-aguf
\n# Complexity\n- Time complexity: O(n^2)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n
mandarin_075
NORMAL
2022-12-10T04:11:56.788437+00:00
2022-12-10T04:11:56.788479+00:00
274
false
\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int sum=0;\n int n=grid.length;\n int max_row[]=new int[n];\n int max_col[]=new int[n];\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n max_row[i]=Math.max(max_row[i],grid[i][j]);\n max_col[j]=Math.max(max_col[j],grid[i][j]);\n }\n }\n\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n sum+=Math.min(max_row[i],max_col[j])-grid[i][j];\n }\n }\n return sum; \n }\n}\n```
2
0
['Java']
0
max-increase-to-keep-city-skyline
C++ solution
c-solution-by-_kitish-6b4q
Intuition\nWe can find the maximum of all the row and column and keep on subtracting the minminum of both rowmax and colmax.\n\n# Approach\nStore the minimum of
_kitish
NORMAL
2022-12-06T17:09:41.320823+00:00
2022-12-06T17:09:41.320897+00:00
920
false
# Intuition\nWe can find the maximum of all the row and column and keep on subtracting the minminum of both rowmax and colmax.\n\n# Approach\nStore the minimum of row and col in vector<pair<int,int>> and keep on subtracting the minimum of rowmax and colmax from each element because we\'ve to maintain the skyline.\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n = grid.size(), ans = 0;\n vector<pair<int,int>> v(n,{-1,-1});\n for(int i=0; i<n; ++i){\n for(int j=0; j<n; ++j){\n v[i].first = max(v[i].first,grid[i][j]);\n v[j].second = max(v[j].second,grid[i][j]);\n }\n }\n for(int i=0,k=0; i<n; ++i,++k){\n for(int j=0; j<n; ++j)\n ans += min(v[i].first,v[j].second) - grid[i][j];\n }\n return ans;\n }\n};\n```
2
0
['Array', 'Greedy', 'C++']
0
max-increase-to-keep-city-skyline
java Clear Solution
java-clear-solution-by-solver_ss-9cpw
Code\n\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int sum =0;\n for (int i = 0 ;i< grid.length;i++){\n
Solver_sS
NORMAL
2022-12-03T12:24:16.884326+00:00
2022-12-03T12:24:16.884365+00:00
434
false
# Code\n```\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int sum =0;\n for (int i = 0 ;i< grid.length;i++){\n for (int j =0 ;j<grid[i].length;j++){\n int old = grid[i][j];\n grid[i][j] = Math.min(rowMax(grid[i]),colMax(grid, j));\n sum += (grid[i][j] - old);\n }\n }\n return sum;\n }\n\n private int colMax(int[][] grid, int j) {\n int max =0;\n int row =0;\n for (int z=0;z< grid.length;z++){\n max = Math.max(max, grid[row][j]);\n row++;\n }\n return max;\n }\n\n private int rowMax(int[] ints) {\n return Arrays.stream(ints).max().getAsInt();\n }\n}\n```
2
0
['Java']
0
max-increase-to-keep-city-skyline
easy java solution
easy-java-solution-by-viveksharma10-nj0q
\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] g) {\n int[][] p=new int[g.length][2];\n int m=0;\n for(int i=0;i<g.len
viveksharma10
NORMAL
2022-10-04T20:28:03.585739+00:00
2022-10-04T20:28:03.585780+00:00
17
false
```\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] g) {\n int[][] p=new int[g.length][2];\n int m=0;\n for(int i=0;i<g.length;i++)\n { \n m=g[i][0];\n for(int j=1;j<g.length;j++)\n {\n if(m<g[i][j])\n m=g[i][j];\n }\n p[i][1]=m;\n \n m=g[0][i];\n for(int j=1;j<g.length;j++)\n {\n if(m<g[j][i])\n m=g[j][i];\n }\n p[i][0]=m;\n }\n \n int c=0;\n for(int i=0;i<g.length;i++)\n {\n for(int j=0;j<g.length;j++)\n {\n System.out.println(Math.min(p[i][0],p[j][1]));\n c+=Math.min(p[i][0],p[j][1])-g[i][j];\n }\n }\n return c;\n }\n}\n```
2
0
['Java']
0
max-increase-to-keep-city-skyline
Java Solution 0ms runtime and faster than 100% with 4 points explanation.
java-solution-0ms-runtime-and-faster-tha-jyhu
\n// Max Increase to Keep City Skyline\n// https://leetcode.com/problems/max-increase-to-keep-city-skyline/\n\nclass Solution {\n public int maxIncreaseKeepi
aayushkumar20
NORMAL
2022-05-29T05:37:54.243454+00:00
2022-05-29T05:37:54.243498+00:00
201
false
```\n// Max Increase to Keep City Skyline\n// https://leetcode.com/problems/max-increase-to-keep-city-skyline/\n\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int[] rowMax = new int[grid.length];\n int[] colMax = new int[grid[0].length];\n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid[0].length; j++) {\n rowMax[i] = Math.max(rowMax[i], grid[i][j]);\n colMax[j] = Math.max(colMax[j], grid[i][j]);\n }\n }\n int sum = 0;\n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid[0].length; j++) {\n sum += Math.min(rowMax[i], colMax[j]) - grid[i][j];\n }\n }\n return sum; \n }\n}\n```\n\n## Explanation.\n\n1. First we\'ll find max value in each rows and columns.\n2. Next we\'ll find minimum value in each rows and columns.\n3. Then we need to find the difference between min value in each row and column and current value in the grid.\n4. Add the difference to the sum.
2
0
['Java']
0
max-increase-to-keep-city-skyline
Java Easy Understsnding Self Expalantory
java-easy-understsnding-self-expalantory-b7cg
\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n List<Integer> rowMax = new ArrayList<>();\n List<Integer> colMax =
bharat194
NORMAL
2022-04-10T14:48:13.485565+00:00
2022-04-10T14:48:13.485608+00:00
174
false
```\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n List<Integer> rowMax = new ArrayList<>();\n List<Integer> colMax = new ArrayList<>();\n for(int i=0;i<grid.length;i++){\n int[] max = max(grid,i,i);\n rowMax.add(max[0]);\n colMax.add(max[1]);\n }\n int res = 0;\n for(int i=0;i<grid.length;i++){\n int row = rowMax.get(i);\n for(int j=0;j<grid.length;j++){\n int col = colMax.get(j);\n res += Math.abs(grid[i][j] - Math.min(col,row));\n }\n }\n return res;\n }\n public int[] max(int[][] grid,int row, int col){\n int maxr = -1,maxc=-1;\n for(int i=0;i<grid.length;i++) maxr = Math.max(grid[row][i],maxr);\n for(int i=0;i<grid.length;i++) maxc = Math.max(grid[i][col],maxc);\n return new int[]{maxr,maxc};\n }\n}\n```
2
0
['Java']
0
max-increase-to-keep-city-skyline
C++ easy approach with explanation
c-easy-approach-with-explanation-by-shar-0ai8
It is a simple problem with tricky question.\n\n*******************************************EXPLANATION******************************************************\n\n
sharathkumarKA
NORMAL
2022-02-28T06:10:44.642939+00:00
2022-02-28T06:24:31.248956+00:00
75
false
It is a simple problem with tricky question.\n``` \n*******************************************EXPLANATION******************************************************\n\n Max row\n 3 0 8 4 8\n 2 4 5 7 7\n 9 2 6 3 9\n 0 3 1 0 3\n\t\t \nMax col 9 4 8 7\n\nnow consider for grid[0][0](i.e 3) \nthe maximum no that can be added to it inoder to maintain the sky view will be\nans = min(max ele in that row, max ele in that column) - that ele(i.e3)\ntherefore ans is the max no that can be added to grid[0][0] that will not affect the original sky view.\n\nsimilarly do it for each cell in the grid and add them and return it;\n\n```\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n vector<int> row ;\n int rowsum=INT_MIN;\n vector<int> col ;\n int colsum=INT_MIN;\n for(int i=0;i<grid.size();i++)\n {\n for(int j=0;j<grid[0].size();j++)\n {\n rowsum= max(rowsum,grid[i][j]);\n colsum= max(colsum,grid[j][i]);\n }\n row.push_back(rowsum);\n rowsum=INT_MIN;\n col.push_back(colsum);\n colsum=INT_MIN;\n }\n int count =0;\n for(int i=0;i<grid.size();i++)\n {\n for(int j=0;j<grid[0].size();j++)\n {\n count+= abs(min(col[j],row[i])-grid[i][j]);\n }\n }\n return count;\n }
2
0
[]
0
max-increase-to-keep-city-skyline
[C++] simple solution
c-simple-solution-by-tinfu330-bhgc
\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n = grid.size();\n \n vector<int> rMax (n
tinfu330
NORMAL
2022-01-24T06:40:02.103821+00:00
2022-01-24T06:40:02.103854+00:00
117
false
```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n = grid.size();\n \n vector<int> rMax (n, INT_MIN);\n vector<int> cMax (n, INT_MIN);\n \n for (int r = 0; r < n; r++) {\n for (int c = 0; c < n; c++) {\n rMax[r] = max(rMax[r], grid[r][c]);\n cMax[c] = max(cMax[c], grid[r][c]);\n }\n }\n \n int res = 0;\n for (int r = 0; r < n; r++) {\n for (int c = 0; c < n; c++) {\n res += min(rMax[r], cMax[c]) - grid[r][c];\n }\n }\n \n return res;\n }\n};\n```
2
0
['C', 'C++']
0
max-increase-to-keep-city-skyline
EASY C++ SOLUTION | FASTER THAN 97.85%
easy-c-solution-faster-than-9785-by-kary-cmd1
\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n = grid.size(), ans = 0;\n vector<int> r(n), c(
karygauss03
NORMAL
2021-08-03T19:52:04.917165+00:00
2021-08-03T19:52:04.917225+00:00
77
false
```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n = grid.size(), ans = 0;\n vector<int> r(n), c(n);\n \n for (int i = 0 ; i < n ; i++){\n for (int j = 0 ; j < n ; j++){\n r[i] = max(r[i], grid[i][j]);\n c[j] = max(c[j], grid[i][j]);\n }\n } \n \n for (int i = 0 ; i < n ; i++){\n for (int j = 0 ; j < n ; j++){\n ans += min(r[i], c[j]) - grid[i][j];\n }\n }\n return ans;\n }\n};\n```
2
0
[]
0
max-increase-to-keep-city-skyline
C++
c-by-harshattree-9d7j
\nint maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n vector<int> N;\n vector<int> E;\n \n int a;\n int ans=0;\n
HarshAttree
NORMAL
2021-07-19T06:25:43.377982+00:00
2021-07-19T06:25:43.378025+00:00
59
false
```\nint maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n vector<int> N;\n vector<int> E;\n \n int a;\n int ans=0;\n int max=0;\n int b;\n for(int i=0;i<grid.size();i++){\n max=0;\n for(int j=0;j<grid.size();j++){\n if(grid[j][i]>max){\n max=grid[j][i];\n }\n }\n E.push_back(max);\n }\n for(int i=0;i<grid.size();i++){\n max=0;\n for(int j=0;j<grid.size();j++){\n if(grid[i][j]>max){\n max=grid[i][j];\n }\n }\n N.push_back(max);\n }\n for(int i=0;i<grid.size();i++){\n for(int j=0;j<grid.size();j++){\n if(E[j]>N[i]){\n a=N[i]-grid[i][j];\n ans=ans+a;\n }else{\n a=E[j]-grid[i][j];\n ans=ans+a;\n }\n }\n }\n return ans;\n }\n```
2
0
[]
0
max-increase-to-keep-city-skyline
C++ 97% FASTER EASY SOLUTION
c-97-faster-easy-solution-by-amitsaxena0-13dd
Find maximum heights row wise and column wise, then take minimum of both and find the difference with each block\'s heights:\n\n\n int maxIncreaseKeepingSkyline
amitsaxena098
NORMAL
2021-07-02T06:35:12.196595+00:00
2021-07-02T06:35:12.196638+00:00
116
false
Find maximum heights row wise and column wise, then take minimum of both and find the difference with each block\'s heights:\n\n```\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n \n vector<int> maxHeightsRow(grid.size(),0);\n vector<int> maxHeightsCol(grid[0].size(), 0);\n \n for(int i = 0; i < grid.size(); i++)\n {\n for(int j = 0; j < grid[0].size(); j++)\n {\n maxHeightsRow[i] = max(maxHeightsRow[i], grid[i][j]);\n maxHeightsCol[i] = max(maxHeightsCol[i], grid[j][i]);\n }\n }\n \n \n int diff = 0;\n \n for(int i = 0; i < grid.size(); i++)\n {\n for(int j = 0; j < grid[0].size(); j++)\n {\n diff += min(maxHeightsRow[i], maxHeightsCol[j]) - grid[i][j];\n \n }\n \n }\n \n return diff;\n \n }\n\t```
2
0
[]
1
max-increase-to-keep-city-skyline
[Python] Solution beats 99.45%
python-solution-beats-9945-by-dexderp1-s94v
\n\n def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int\n\t cols = list(zip(*grid))\n rowMaxes = [ max(row) for row in grid ]\n
dexderp1
NORMAL
2019-12-19T02:49:33.796980+00:00
2019-12-19T02:49:33.797016+00:00
236
false
\n\n def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int\n\t cols = list(zip(*grid))\n rowMaxes = [ max(row) for row in grid ]\n colMaxes = [ max(col) for col in cols ]\n \n maxIncrease = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n maxIncrease += min(rowMaxes[i],colMaxes[j]) - grid[i][j]\n \n return maxIncrease
2
0
[]
0
max-increase-to-keep-city-skyline
scala functional solution
scala-functional-solution-by-gyarish-wad2
\nobject Solution {\n def maxIncreaseKeepingSkyline(grid: Array[Array[Int]]): Int = {\n \n val skyLineTop = grid.map(row => row.max)\n v
gyarish
NORMAL
2019-11-09T12:16:20.148574+00:00
2019-11-09T12:16:20.148608+00:00
71
false
```\nobject Solution {\n def maxIncreaseKeepingSkyline(grid: Array[Array[Int]]): Int = {\n \n val skyLineTop = grid.map(row => row.max)\n val skyLineLeft = grid.transpose.map(row => row.max)\n \n val seq = for {\n i <- grid.indices\n j <- grid(i).indices\n } yield {\n Math.min(skyLineTop(i), skyLineLeft(j)) - grid(i)(j)\n }\n \n seq.sum\n }\n}\n```
2
0
['Scala']
0
max-increase-to-keep-city-skyline
Python Numpy Implementation
python-numpy-implementation-by-msminhas-ai71
\n\nimport numpy as np\nclass Solution:\n def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:\n argrid = np.array(grid)\n tbsky
msminhas
NORMAL
2019-09-30T18:45:14.966510+00:00
2019-09-30T18:45:14.966563+00:00
183
false
\n```\nimport numpy as np\nclass Solution:\n def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:\n argrid = np.array(grid)\n tbsky = np.max(argrid,axis=0)\n lrsky = np.max(argrid,axis=1)\n mesh = np.meshgrid(tbsky,lrsky)\n maxmesh = np.min(mesh,axis=0)\n increment = np.sum(maxmesh-argrid)\n return int(increment)\n```
2
0
[]
1
max-increase-to-keep-city-skyline
[Java] O(n) solution beats 100%
java-on-solution-beats-100-by-olsh-9lcd
\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int[] horizontal = new int[grid[0].length];\n int[] vertical = new
olsh
NORMAL
2019-07-08T20:51:49.746870+00:00
2019-07-09T09:39:34.845218+00:00
694
false
```\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int[] horizontal = new int[grid[0].length];\n int[] vertical = new int[grid.length];\n for (int i=0;i<grid.length;i++){\n for (int j=0;j<grid[0].length;j++){\n horizontal[j]=Math.max(horizontal[j],grid[i][j]);\n vertical[i]=Math.max(vertical[i],grid[i][j]);\n }\n }\n int res = 0;\n for (int i=0;i<grid.length;i++){\n for (int j=0;j<grid[0].length;j++){\n res+=Math.min(horizontal[j],vertical[i]) - grid[i][j];\n }\n }\n return res;\n }\n}\n```
2
1
[]
3
max-increase-to-keep-city-skyline
Python 24ms Code
python-24ms-code-by-dacheng0413-u9pz
\nclass Solution(object):\n def maxIncreaseKeepingSkyline(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n """\n
dacheng0413
NORMAL
2019-02-15T04:42:39.536623+00:00
2019-02-15T04:42:39.536672+00:00
519
false
```\nclass Solution(object):\n def maxIncreaseKeepingSkyline(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n """\n top_max=[]\n left_max=[]\n for i in range(len(grid)):\n left_max.append(max(grid[i]))\n for i in range(len(grid[0])):\n top_max.append(max(item[i] for item in grid))\n result = 0\n for i in range(len(top_max)):\n for j in range(len(left_max)):\n if top_max[i] < left_max[j]:\n result += top_max[i] - grid[i][j]\n else:\n result += left_max[j] - grid[i][j]\n return result\n\t```
2
0
['Python']
1
max-increase-to-keep-city-skyline
Simple Python Solution
simple-python-solution-by-ciufi23-x9zp
\nclass Solution:\n def maxIncreaseKeepingSkyline(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n """\n t
ciufi23
NORMAL
2019-01-09T15:56:37.286594+00:00
2019-01-09T15:56:37.286636+00:00
198
false
```\nclass Solution:\n def maxIncreaseKeepingSkyline(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n """\n total = 0\n N = len(grid)\n \n # Can also do this by iterating once through the matrix\n max_row = [max(row) for row in grid]\n max_col = [max([row[j] for row in grid]) for j in range(N)]\n \n for i in range(N):\n for j in range(N):\n total += min(max_col[j], max_row[i]) - grid[i][j]\n \n return total\n```
2
0
[]
1
max-increase-to-keep-city-skyline
Rust Solution, 0ms
rust-solution-0ms-by-terakilobyte-z6mj
\nimpl Solution {\n pub fn max_increase_keeping_skyline(grid: Vec<Vec<i32>>) -> i32 {\n let mut row_maxes: Vec<i32> = (0..grid.len()).into_iter().map(
terakilobyte
NORMAL
2019-01-04T13:54:54.081000+00:00
2019-01-04T13:54:54.081044+00:00
113
false
```\nimpl Solution {\n pub fn max_increase_keeping_skyline(grid: Vec<Vec<i32>>) -> i32 {\n let mut row_maxes: Vec<i32> = (0..grid.len()).into_iter().map(|_| 0).collect();\n let mut col_maxes: Vec<i32> = (0..grid[0].len()).into_iter().map(|_| 0).collect();\n for i in 0..grid.len() {\n row_maxes[i] = *grid[i].iter().max().unwrap();\n for j in 0..grid[i].len() {\n col_maxes[j] = col_maxes[j].max(grid[i][j]);\n }\n }\n let mut total_increase = 0;\n for i in 0..row_maxes.len() {\n for j in 0.. col_maxes.len() {\n total_increase += row_maxes[i].min(col_maxes[j]) - grid[i][j];\n }\n }\n total_increase\n }\n}\n```
2
0
[]
1
max-increase-to-keep-city-skyline
Python solution
python-solution-by-zitaowang-ye9w
\nclass Solution(object):\n def maxIncreaseKeepingSkyline(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n """\n
zitaowang
NORMAL
2018-08-30T01:05:40.425486+00:00
2018-08-30T01:05:40.425566+00:00
297
false
```\nclass Solution(object):\n def maxIncreaseKeepingSkyline(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n """\n rowNum = len(grid)\n colNum = len(grid[0])\n rowMax = [max(grid[i]) for i in range(rowNum)]\n colMax = [max([grid[j][i] for j in range(rowNum)]) for i in range(colNum)]\n res = 0\n for i in range(rowNum):\n for j in range(colNum):\n res += min(rowMax[i],colMax[j]) - grid[i][j]\n return res\n```
2
0
[]
0
max-increase-to-keep-city-skyline
javascript ES6 step by step 60 ms
javascript-es6-step-by-step-60-ms-by-flo-khvy
\nconst maxIncreaseKeepingSkyline = (grid) => {\n let rowMaxes = [];\n let colMaxes = [];\n \n // max each row\n grid.map(row => rowMaxes.push(Ma
flo92105
NORMAL
2018-05-18T22:26:09.815312+00:00
2018-05-18T22:26:09.815312+00:00
325
false
```\nconst maxIncreaseKeepingSkyline = (grid) => {\n let rowMaxes = [];\n let colMaxes = [];\n \n // max each row\n grid.map(row => rowMaxes.push(Math.max(...row)));\n \n // transpose from stackoverflow\n const transposedGrid = grid[0].map((col, i) => grid.map(row => row[i]));\n // max each column\n transposedGrid.map(col => colMaxes.push(Math.max(...col)));\n \n // traverse grid => each cell raise till first max\n let sum = 0;\n for (let i = 0; i < grid.length; i++) {\n for (let j = 0; j < grid[0].length; j++) {\n sum += Math.min(rowMaxes[i], colMaxes[j]) - grid[i][j];\n }\n }\n return sum;\n};\n```
2
1
[]
0
max-increase-to-keep-city-skyline
Greedy
greedy-by-akshaypatidar33-xsly
Code
akshaypatidar33
NORMAL
2025-04-10T18:54:24.607352+00:00
2025-04-10T18:54:24.607352+00:00
2
false
# Code ```cpp [] class Solution { public: int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) { int n = grid.size(); vector<int> rmax(n); vector<int> cmax(n); for(int i=0; i<n; i++){ int mr = INT_MIN; int mc = INT_MIN; for(int j=0; j<n; j++){ mr=max(mr, grid[i][j]); mc=max(mc, grid[j][i]); } rmax[i]=mr; cmax[i]=mc; } int ans =0; for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ ans+=(min(rmax[i], cmax[j])) - grid[i][j]; } } return ans; } }; ```
1
0
['Array', 'Greedy', 'Matrix', 'C++']
0
max-increase-to-keep-city-skyline
Beginner-Friendly Solution: Maximize Building Heights Without Changing Skyline
beginner-friendly-solution-maximize-buil-qzgg
✅ IntuitionThe goal is to maximize the height of the buildings without changing the skyline. The skyline is defined by the max height in each row and column.🔥 A
vishwajeetwalekar037
NORMAL
2025-03-29T13:15:46.201766+00:00
2025-03-29T13:15:46.201766+00:00
15
false
### ✅ **Intuition** The goal is to maximize the height of the buildings without changing the skyline. The skyline is defined by the max height in each row and column. ### 🔥 **Approach** 1. **Find Max Heights:** - For each row, find the maximum height. - For each column, find the maximum height. 2. **Calculate Increase:** - For each building, find the minimum of its row and column max height. - Add the difference between this minimum and the current height to the total increase. ### ⏱️ **Complexity** - **Time Complexity:** \(O(n^2)\) → Iterates through all cells twice (once for row max, once for column max). - **Space Complexity:** \(O(1)\) → No extra space used, only a few variables for calculation. # Code ```java [] class Solution { public int maxIncreaseKeepingSkyline(int[][] grid) { int sum = 0; for (int m = 0; m < grid.length; m++) { for (int i = 0; i < grid[m].length; i++) { int rowMax = 0; for (int j = 0; j < grid[m].length; j++) { if (grid[m][j] > rowMax) { rowMax = grid[m][j]; } } int colMax = 0; for (int k = 0; k < grid.length; k++) { if (grid[k][i] > colMax) { colMax = grid[k][i]; } } sum += Math.min(rowMax, colMax) - grid[m][i]; } } return sum; } } ```
1
0
['Java']
0
max-increase-to-keep-city-skyline
Easy solution using for loop|| Beats 100 % || JAVA
easy-solution-using-for-loop-beats-100-j-qt8i
IntuitionApproachComplexity Time complexity: Space complexity: Code
Rajan_Singh01
NORMAL
2025-03-24T15:39:39.427634+00:00
2025-03-24T15:39:39.427634+00:00
37
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 maxIncreaseKeepingSkyline(int[][] arr) { int n = arr.length; int row[] = new int[n]; int col[] = new int[n]; for (int i = 0; i < n; i++) { int max = 0; for (int j = 0; j < n; j++) { if (max < arr[i][j]) { max = arr[i][j]; } } row[i] = max; } for (int i = 0; i < n; i++) { int max = 0; for (int j = 0; j < n; j++) { if (max < arr[j][i]) { max = arr[j][i]; } } col[i] = max; } int sum=0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int a = row[i] > col[j] ? col[j] : row[i] ; if(arr[i][j]<a){ sum+= a - arr[i][j]; } } } return sum; } } ```
1
0
['Array', 'Greedy', 'Matrix', 'Java']
0
max-increase-to-keep-city-skyline
Easy Solution
easy-solution-by-harshulgarg-cqqn
IntuitionIncrease building heights while ensuring the skyline remains unchanged when viewed from the top and sides. The maximum possible height of each building
harshulgarg
NORMAL
2025-01-31T19:47:13.547151+00:00
2025-01-31T19:47:13.547151+00:00
77
false
# Intuition Increase building heights while ensuring the skyline remains unchanged when viewed from the top and sides. The maximum possible height of each building is limited by the highest value in its row and column. # Approach Compute row-wise max (a[]) and column-wise max (b[]). Calculate the original sum of all grid elements. Update each cell to min(row_max[i], col_max[j]) and compute the new sum. Return the difference between the new sum and the original sum. # Complexity - Time complexity: O(n^2) - Space complexity: O(n) # Code ```python3 [] class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: a=[] b=[] s=0 for i in grid: a.append(max(i)) s+=sum(i) for i in range(len(grid)): c=0 for j in range(len(grid)): c=max(c,grid[j][i]) b.append(c) res=0 for i in range(len(a)): for j in range(len(b)): grid[i][j]=min(a[i],b[j]) res+=grid[i][j] return res-s ```
1
0
['Array', 'Python3']
0
max-increase-to-keep-city-skyline
C++ | 100% Faster
c-100-faster-by-user3219pp-0buu
IntuitionApproachComplexity Time complexity: Space complexity: Code
user3219pp
NORMAL
2025-01-26T19:24:58.664385+00:00
2025-01-26T19:24:58.664385+00:00
67
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 maxIncreaseKeepingSkyline(vector<vector<int>>& grid) { int n = grid.size(); vector<int> row(n, 0), col(n , 0); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(grid[i][j] > row[i]) row[i] = grid[i][j]; if(grid[i][j] > col[j]) col[j] = grid[i][j]; } } int cnt = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { int mini = min(col[j], row[i]); cnt = cnt + (mini - grid[i][j]); } } return cnt; } }; ```
1
0
['C++']
0
max-increase-to-keep-city-skyline
easy code
easy-code-by-red_viper-ieb3
IntuitionApproachComplexity Time complexity: O(N^ 2) Space complexity: O(N) Code
red_viper
NORMAL
2025-01-02T12:42:14.976582+00:00
2025-01-02T12:42:14.976582+00:00
23
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^ 2) <!-- 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 maxIncreaseKeepingSkyline(vector<vector<int>>& grid) { int row = grid.size(); vector< int > rm ; vector<int> cm ; for ( int i = 0 ; i < row ; i++) { int m1 = INT_MIN, m2 =INT_MIN; for ( int j= 0 ; j < row ;j++) { if( m1 < grid[i][j]) m1 = grid[i][j]; if( m2 < grid[j][i]) m2 = grid[j][i]; } rm.push_back( m1); cm.push_back ( m2); } for( const auto & i : rm) cout<<i<<" "; for( const auto & i : cm) cout<<i<<" "; int count = 0; for ( int i = 0 ; i < row ; i++) { for ( int j= 0 ; j < row ;j++) { count += min (rm [i] , cm [j] ) - grid[i] [j]; } } return count; } }; ```
1
0
['C++']
0
max-increase-to-keep-city-skyline
Simple Approach Greedily
simple-approach-greedily-by-dhruv_6395-duek
IntuitionApproach :Find maximums of a particular row and corresponding column and then take minimum of it and increment the grid[i][j] value upto minimum of max
Dhruv_0036
NORMAL
2024-12-30T09:42:02.923825+00:00
2024-12-30T09:42:02.923825+00:00
13
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach : <!-- Describe your approach to solving the problem. --> Find maximums of a particular row and corresponding column and then take minimum of it and increment the grid[i][j] value upto minimum of maximums + 1. # Complexity - Time complexity: O(N*2) <!-- 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 sumOfMatrix(vector<vector<int>>& ans) { int sum = 0; for(int i=0; i<ans.size(); i++) { for(int j=0; j<ans[0].size(); j++) sum += ans[i][j]; } return sum; } int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) { int sum1 = sumOfMatrix(grid); for(int i=0; i<grid.size(); i++) { for(int j=0; j<grid[0].size(); j++) { int rmax = 0, cmax = 0; for(int k=0; k<grid[0].size(); k++) rmax = max(rmax, grid[i][k]); for(int k=0; k<grid.size(); k++) cmax = max(cmax, grid[k][j]); while(grid[i][j]<min(rmax,cmax)) grid[i][j]++; } } int sum2 = sumOfMatrix(grid); return (sum2-sum1); } }; ```
1
0
['Array', 'Greedy', 'Matrix', 'C++']
0
max-increase-to-keep-city-skyline
C++ Easiest way Solution
c-easiest-way-solution-by-jeetgajera-e9q9
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Jeetgajera
NORMAL
2024-09-11T05:07:43.226510+00:00
2024-09-11T05:07:43.226535+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity : O(N*N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity : O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n = grid.size();\n int maxSum = 0;\n\n vector<int> maxCol (n, INT_MIN) ;\n vector<int> maxRow (n, INT_MIN);\n\n for(int i = 0; i < n; i++){\n for(int j = 0; j < n; j++){\n maxRow[i] = max(maxRow[i], grid[i][j]);\n maxCol[j] = max(maxCol[j], grid[i][j]);\n }\n }\n\n for(int i = 0; i < n; i++){\n for(int j = 0; j < n; j++){\n maxSum += (min(maxRow[i], maxCol[j]) - grid[i][j]);\n }\n }\n return maxSum;\n }\n};\n```
1
0
['Greedy', 'Matrix', 'C++']
0
max-increase-to-keep-city-skyline
Straightforward Easy C++ Solution
straightforward-easy-c-solution-by-bhart-3mx6
Intuition\nIn the problem, we\'re asked to modify the grid such that the new grid has the same skyline when viewed from both the top/bottom and left/right.\n\nM
bharti_pd
NORMAL
2024-08-13T16:35:46.806678+00:00
2024-08-13T16:37:54.868978+00:00
33
false
# Intuition\nIn the problem, we\'re asked to modify the grid such that the new grid has the same skyline when viewed from both the top/bottom and left/right.\n\nMy observation during the dry run was that the grid can be altered such that the new height of each building is determined by the smaller value between the maximum values of its corresponding row and column. This way, the skyline is preserved, and the increase in height is maximized.\n\n# Approach\n The approach is straightforward:\n\n- Create two vectors of size n to store the maximum values from each row (maxRow) and each column (maxCol). Traverse the grid to populate these vectors.\n- In the second loop, calculate the total possible height increase (maxSum) by taking the minimum of the corresponding row and column max values and subtracting the original grid value. This gives the additional height that can be added to each building without altering the skyline. \n\n# Complexity\n- Time complexity: O(n*n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int n = grid.size();\n int maxSum = 0;\n\n vector<int> maxCol (n, INT_MIN) ;\n vector<int> maxRow (n, INT_MIN);\n\n for(int i = 0; i < n; i++){\n for(int j = 0; j < n; j++){\n maxRow[i] = max(maxRow[i], grid[i][j]);\n maxCol[j] = max(maxCol[j], grid[i][j]);\n }\n }\n\n for(int i = 0; i < n; i++){\n for(int j = 0; j < n; j++){\n maxSum += (min(maxRow[i], maxCol[j]) - grid[i][j]);\n }\n }\n return maxSum;\n }\n};\n```
1
0
['Array', 'Greedy', 'Matrix', 'C++']
0
max-increase-to-keep-city-skyline
EASY C++ SOLUTION ✅✅🔥🔥
easy-c-solution-by-baladharun-43uj
Intuition\n1. we have to calculate how much each building can be increased without changing the skyline, ensuring that the increase respects the maximum heights
Baladharun
NORMAL
2024-07-05T08:56:08.769585+00:00
2024-07-05T08:56:08.769620+00:00
10
false
# Intuition\n1. we have to calculate how much each building can be increased without changing the skyline, ensuring that the increase respects the maximum heights from both the row and column perspectives.\n1. Finally, it sums up all the possible increases and returns the result.\n2. It can be done by **min(max(row[i],column[j])) - grid[i][j]** which indicates the maximum height to be viewed along different sides and min in for without affecting another direction\n\n# Complexity\n- Time complexity:O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n vector<int> row(grid.size(),INT_MIN);\n vector<int> column(grid.size(),INT_MIN);\n int result = 0;\n for(int i=0;i<grid.size();i++)\n {\n for(int j=0;j<grid[i].size();j++)\n row[i] = max(row[i],grid[i][j]);\n }\n for(int i=0;i<grid.size();i++)\n {\n for(int j=0;j<grid[i].size();j++)\n column[i] = max(column[i],grid[j][i]);\n }\n for(int i=0;i<grid.size();i++)\n {\n for(int j=0;j<grid[i].size();j++)\n {\n result += min(row[i],column[j]) - grid[i][j];\n }\n }\n return result;\n }\n};\n```
1
0
['C++']
0
max-increase-to-keep-city-skyline
Easy C++ Solution | Beats 77%
easy-c-solution-beats-77-by-deepak2k03-vl0z
Intuition\nIt can be solved greedily\n\n# Approach\nFor every element find minimum of maximum elements in that row and column, i.e and subtract that element fro
deepak2k03
NORMAL
2024-05-26T02:06:41.867799+00:00
2024-05-26T02:06:41.867819+00:00
6
false
# Intuition\nIt can be solved greedily\n\n# Approach\nFor every element find minimum of maximum elements in that row and column, i.e and subtract that element from that and add the result in a storing variable.\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int c=0;\n vector<int>rows,cols;\n for(int i=0;i<grid.size();i++){\n int m=0;\n for(int j=0;j<grid.size();j++){\n m=max(m,grid[i][j]);\n }\n rows.push_back(m);\n }\n for(int i=0;i<grid.size();i++){\n int m=0;\n for(int j=0;j<grid.size();j++){\n m=max(m,grid[j][i]);\n }\n cols.push_back(m);\n }\n\n for(int i=0;i<grid.size();i++){\n for(int j=0;j<grid.size();j++){\n c+=(min(rows[i],cols[j])-grid[i][j]);\n }\n }\n return c;\n }\n};\n```
1
0
['C++']
0
max-increase-to-keep-city-skyline
Simple Approach: Maximize Building Heights for Unchanged Skylines
simple-approach-maximize-building-height-7mdr
Explanation of the Problem\nThink of a city with buildings of different heights arranged like a grid. The goal is to make the buildings taller but without chang
shrutika-07
NORMAL
2024-02-22T11:34:21.823720+00:00
2024-02-22T11:34:21.823744+00:00
57
false
# Explanation of the Problem\nThink of a city with buildings of different heights arranged like a grid. The goal is to make the buildings taller but without changing how the city looks when you see it from any side. We want to figure out the maximum amount by which we can increase the heights of the buildings without altering the overall appearance of the city.\n\n**Increase building heights without changing skyline. Calculate max increase for each building by considering max heights in its row and column. Return total increase.**\n\n---\n\n# Approach\n**1. Find Maximum Heights:**\n- Iterate through each row to find the maximum height in that row.\n- Store these maximum heights in an array (maxInRow).\n- Similarly, iterate through each column to find the maximum height in that column.\n- Store these maximum heights in another array (maxInCol).\n\n**2. Calculate Maximum Allowable Increase:**\n- Iterate through each building in the grid.\n- For each building, find the minimum between the maximum height in its row (maxInRow) and the maximum height in its column (maxInCol).\n- This minimum represents the maximum allowable increase in height for that building without changing the skyline.\n\n**3. Update Building Heights:**\n- Update the height of each building to the calculated maximum allowable increase.\n- Accumulate the total height increase during this process.\n\n**4. Return Result:**\n- Return the total height increase as the final result.\n\n---\n# Complexity\n- Time Complexity:\n`O(n^2)`\n\n- Space Complexity:\n`O(n)`\n\n\n---\n\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n int rows = grid.size();\n int cols = grid[0].size();\n\n vector<int> maxInRow(rows, 0);\n vector<int> maxInCol(cols, 0);\n\n // Find Maximum Height of Building in Row\n for (int i = 0; i < rows; ++i) {\n int maxRow = 0;\n for (int j = 0; j < rows; ++j) {\n maxRow = max(maxRow, grid[i][j]);\n }\n maxInRow[i] = maxRow;\n }\n\n // Find Maximum Height of Building in Col\n for (int i = 0; i < cols; ++i) {\n int maxCol = 0;\n for (int j = 0; j < rows; ++j) {\n maxCol = max(maxCol, grid[j][i]);\n }\n maxInCol[i] = maxCol;\n }\n\n // Increase the Height of the Buildings\n int sum = 0;\n for (int i = 0; i < rows; ++i) {\n for (int j = 0; j < cols; ++j) {\n int height = min(maxInRow[i], maxInCol[j]);\n int difference = height - grid[i][j];\n sum += difference;\n grid[i][j] = height;\n }\n }\n\n return sum;\n }\n};\n```\n```Java []\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int[] maxInRow = new int[grid.length];\n int[] maxInCol = new int[grid[0].length];\n\n // Find Maximum Height of Building in Row\n for(int i = 0; i < grid.length; i++) {\n int maxRow = Integer.MIN_VALUE;\n for(int j = 0; j < grid[0].length; j++) {\n maxRow = Math.max(maxRow, grid[i][j]);\n }\n maxInRow[i] = maxRow;\n }\n\n // Find Maximum Height of Building in Col\n for(int i = 0; i < grid.length; i++) {\n int maxCol = Integer.MIN_VALUE;\n for(int j = 0; j < grid[0].length; j++) {\n maxCol = Math.max(maxCol, grid[j][i]);\n }\n maxInCol[i] = maxCol;\n }\n \n // Increase the Height of the Buildings\n int sum = 0;\n for(int i = 0; i < grid.length; i++) {\n for(int j = 0; j < grid[0].length; j++) {\n int height = Math.min(maxInRow[i], maxInCol[j]);\n int difference = height - grid[i][j];\n sum += difference;\n grid[i][j] = height;\n }\n }\n\n return sum;\n }\n}\n```\n\n---\n\n# If you find this solution helpful, kindly consider upvoting!\n\n---\n\n\n
1
0
['Array', 'Math', 'Greedy', 'Matrix', 'C++', 'Java']
0
max-increase-to-keep-city-skyline
Swift solution
swift-solution-by-azm819-rwkx
Complexity\n- Time complexity: O(n * m)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n + m)\n Add your space complexity here, e.g. O(n)
azm819
NORMAL
2024-02-06T14:22:51.189110+00:00
2024-02-06T14:22:51.189131+00:00
3
false
# Complexity\n- Time complexity: $$O(n * m)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n + m)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n func maxIncreaseKeepingSkyline(_ grid: [[Int]]) -> Int {\n var rowMax = Array(repeating: 0, count: grid.count)\n var colMax = Array(repeating: 0, count: grid[0].count)\n for i in 0 ..< grid.count {\n for j in 0 ..< grid[0].count {\n rowMax[i] = max(rowMax[i], grid[i][j])\n colMax[j] = max(colMax[j], grid[i][j])\n }\n }\n\n var result = 0\n for i in 0 ..< grid.count {\n for j in 0 ..< grid[0].count {\n result += min(rowMax[i], colMax[j]) - grid[i][j]\n }\n }\n return result\n }\n}\n```
1
0
['Array', 'Greedy', 'Swift', 'Matrix']
0
max-increase-to-keep-city-skyline
🔥Beats 100% 🔥 Simple & best java solution.
beats-100-simple-best-java-solution-by-r-tv5b
Complexity\n- Time complexity : 0 MS\n Add your time complexity here, e.g. O(n) \n\n- Space complexity : 43 MB\n Add your space complexity here, e.g. O(n) \n\n#
Ronak_Thesiya
NORMAL
2023-09-25T13:49:03.470436+00:00
2023-09-25T13:49:03.470457+00:00
554
false
# Complexity\n- Time complexity : 0 MS\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity : 43 MB\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int n=grid.length;\n int arr1[]=new int[n];\n int arr2[]=new int[n];\n\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n if(arr2[i]<grid[i][j]) arr2[i]=grid[i][j];\n if(arr1[j]<grid[i][j]) arr1[j]=grid[i][j];\n }\n }\n\n int ans=0;\n int m=0;\n \n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n m=Math.min(arr2[i],arr1[j]);\n if(grid[i][j]<m) ans+=(m-grid[i][j]);\n }\n }\n\n return ans;\n }\n}\n```\n```\n```\n- # Any question! write in comment box.\n```
1
0
['Java']
1