From f121e8f11c7072b486603a2ede716e86308fb970 Mon Sep 17 00:00:00 2001 From: ASR Date: Sun, 12 Oct 2025 11:08:10 +0530 Subject: [PATCH] feat: fix-issue-394 --- .../cpp-code.cpp" | 40 ++++++ .../java-code.java" | 42 ++++++ .../markdown.md" | 126 ++++++++++++++++++ .../python-code.py" | 36 +++++ 4 files changed, 244 insertions(+) create mode 100644 "Graphs/The-Kingdom\342\200\231s-Gold-Vault/cpp-code.cpp" create mode 100644 "Graphs/The-Kingdom\342\200\231s-Gold-Vault/java-code.java" create mode 100644 "Graphs/The-Kingdom\342\200\231s-Gold-Vault/markdown.md" create mode 100644 "Graphs/The-Kingdom\342\200\231s-Gold-Vault/python-code.py" diff --git "a/Graphs/The-Kingdom\342\200\231s-Gold-Vault/cpp-code.cpp" "b/Graphs/The-Kingdom\342\200\231s-Gold-Vault/cpp-code.cpp" new file mode 100644 index 00000000..ba864ec7 --- /dev/null +++ "b/Graphs/The-Kingdom\342\200\231s-Gold-Vault/cpp-code.cpp" @@ -0,0 +1,40 @@ +#include +using namespace std; + +int dfs(int node, vector>& adj, vector& gold, vector& visited) { + visited[node] = true; + int total = gold[node]; + for (int nei : adj[node]) { + if (!visited[nei]) + total += dfs(nei, adj, gold, visited); + } + return total; +} + +int main() { + int n; + cin >> n; + vector gold(n); + for (int i = 0; i < n; i++) cin >> gold[i]; + + int e; + cin >> e; + vector> adj(n); + for (int i = 0; i < e; i++) { + int u, v; + cin >> u >> v; + adj[u].push_back(v); + adj[v].push_back(u); + } + + vector visited(n, false); + int maxGold = 0; + + for (int i = 0; i < n; i++) { + if (!visited[i]) + maxGold = max(maxGold, dfs(i, adj, gold, visited)); + } + + cout << maxGold << endl; + return 0; +} diff --git "a/Graphs/The-Kingdom\342\200\231s-Gold-Vault/java-code.java" "b/Graphs/The-Kingdom\342\200\231s-Gold-Vault/java-code.java" new file mode 100644 index 00000000..7b9aec2e --- /dev/null +++ "b/Graphs/The-Kingdom\342\200\231s-Gold-Vault/java-code.java" @@ -0,0 +1,42 @@ +import java.util.*; + +public class Main { + static int dfs(int node, List> adj, int[] gold, boolean[] visited) { + visited[node] = true; + int total = gold[node]; + for (int nei : adj.get(node)) { + if (!visited[nei]) + total += dfs(nei, adj, gold, visited); + } + return total; + } + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + int n = sc.nextInt(); + int[] gold = new int[n]; + for (int i = 0; i < n; i++) gold[i] = sc.nextInt(); + + int e = sc.nextInt(); + List> adj = new ArrayList<>(); + for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); + + for (int i = 0; i < e; i++) { + int u = sc.nextInt(); + int v = sc.nextInt(); + adj.get(u).add(v); + adj.get(v).add(u); + } + + boolean[] visited = new boolean[n]; + int maxGold = 0; + + for (int i = 0; i < n; i++) { + if (!visited[i]) + maxGold = Math.max(maxGold, dfs(i, adj, gold, visited)); + } + + System.out.println(maxGold); + } +} diff --git "a/Graphs/The-Kingdom\342\200\231s-Gold-Vault/markdown.md" "b/Graphs/The-Kingdom\342\200\231s-Gold-Vault/markdown.md" new file mode 100644 index 00000000..3dee91e2 --- /dev/null +++ "b/Graphs/The-Kingdom\342\200\231s-Gold-Vault/markdown.md" @@ -0,0 +1,126 @@ +## DSA Question: The Kingdom’s Gold Vault + +--- + +## Problem +In the prosperous land of **AlgoLand**, there are `N` rooms connected by tunnels. Each room contains a certain amount of gold. The kingdom has decided to assign a **single guard** who can start in **any room** and move through **adjacent rooms** (connected by tunnels) **without revisiting** any room. + +The guard’s objective is to **maximize the total gold collected** during the journey. + +You are given: +- An integer `N` — the number of rooms. +- An array `gold[]` of length `N`, where `gold[i]` represents the amount of gold in room `i`. +- A list of tunnels represented as pairs `[u, v]` meaning there is a tunnel between room `u` and room `v`. + +Return the **maximum gold** the guard can collect following the rules. + +If there are **no tunnels** (rooms are isolated), the answer is simply the **maximum gold value** among all rooms. + +--- + +## Examples + +### Example 1: +**Input:** + + +N = 5 +gold = [2, 5, 7, 1, 3] +tunnels = [[0, 1], [1, 2], [2, 3], [3, 4]] + +**Output:** +`18` + +**Explanation:** +The optimal path is from room `0 → 1 → 2 → 3 → 4`, collecting `2 + 5 + 7 + 1 + 3 = 18`. + +--- + +### Example 2: +**Input:** + + +N = 4 +gold = [10, 20, 30, 40] +tunnels = [[0, 1], [2, 3]] + +**Output:** +`50` + +**Explanation:** +There are two separate vault systems: +- Vault 1: `0 ↔ 1` → total = `30` +- Vault 2: `2 ↔ 3` → total = `70` +The guard should choose the second group of rooms for maximum gold. + +--- + +### Example 3: +**Input:** + + +N = 3 +gold = [5, 1, 2] +tunnels = [] + +**Output:** +`5` + +**Explanation:** +No tunnels exist, so the guard can only pick one room — the richest one. + +--- + +## Approach + +### 🧩 **Simple / Beginner Approach** +**(Using DFS on each component)** +1. Build an adjacency list for all tunnels. +2. Initialize a `visited` array. +3. For each unvisited node: + - Run a DFS traversal to explore the connected component. + - Sum up the gold in that component. +4. Keep track of the **maximum gold sum** among all components. + +**Return:** the maximum collected gold. + +--- + +### ⚙️ **Medium / Logic Approach** +**(DFS with Path Sum Tracking)** +1. Represent rooms as nodes in a graph. +2. Use DFS to explore all paths **without revisiting** any node. +3. For each path, accumulate gold and backtrack to explore alternate paths. +4. Use memoization to avoid recomputing overlapping subpaths. + +**Idea:** Similar to finding the *maximum path sum* in a graph/tree. + +**Time Complexity:** `O(N + E)` where `E` is the number of tunnels. +**Space Complexity:** `O(N)` for recursion and visited array. + +--- + +### 🚀 **Hard / Optimized Approach** +**(Dynamic Programming on Graph / Tree DP)** +1. Treat the system of tunnels as a forest (set of connected components). +2. For each component, run a **Tree DP** where: + - `dp[node]` = maximum gold collected starting from `node` and moving through unvisited adjacent rooms. + - Update `dp[node]` from children nodes using: + ``` + dp[node] = gold[node] + max(dp[child1], dp[child2], …) + ``` +3. Return the **maximum value** of all `dp[node]` across all components. + +**Optimizations:** +- Avoid recomputation with memoization. +- Detect and skip already processed components. + +**Time Complexity:** `O(N + E)` +**Space Complexity:** `O(N)` + +--- + +## Topics of this Problem +- **Graph Theory** +- **Arrays** +- **Stack (for DFS recursion)** diff --git "a/Graphs/The-Kingdom\342\200\231s-Gold-Vault/python-code.py" "b/Graphs/The-Kingdom\342\200\231s-Gold-Vault/python-code.py" new file mode 100644 index 00000000..bdc27df0 --- /dev/null +++ "b/Graphs/The-Kingdom\342\200\231s-Gold-Vault/python-code.py" @@ -0,0 +1,36 @@ +def dfs(node, adj, gold, visited): + """Depth-First Search to sum up gold in a connected component.""" + visited[node] = True + total = gold[node] + for nei in adj[node]: + if not visited[nei]: + total += dfs(nei, adj, gold, visited) + return total + + +def max_gold_vault(): + """Main function to read input and calculate maximum gold.""" + n = int(input().strip()) + gold = list(map(int, input().strip().split())) + e = int(input().strip()) + + # Build adjacency list + adj = [[] for _ in range(n)] + for _ in range(e): + u, v = map(int, input().strip().split()) + adj[u].append(v) + adj[v].append(u) + + visited = [False] * n + max_gold = 0 + + for i in range(n): + if not visited[i]: + max_gold = max(max_gold, dfs(i, adj, gold, visited)) + + print(max_gold) + + +# Run the program +if __name__ == "__main__": + max_gold_vault() \ No newline at end of file