Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions Graphs/The-Kingdom’s-Gold-Vault/cpp-code.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#include <bits/stdc++.h>
using namespace std;

int dfs(int node, vector<vector<int>>& adj, vector<int>& gold, vector<bool>& 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<int> gold(n);
for (int i = 0; i < n; i++) cin >> gold[i];

int e;
cin >> e;
vector<vector<int>> 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<bool> 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;
}
42 changes: 42 additions & 0 deletions Graphs/The-Kingdom’s-Gold-Vault/java-code.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import java.util.*;

public class Main {
static int dfs(int node, List<List<Integer>> 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<List<Integer>> 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);
}
}
126 changes: 126 additions & 0 deletions Graphs/The-Kingdom’s-Gold-Vault/markdown.md
Original file line number Diff line number Diff line change
@@ -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)**
36 changes: 36 additions & 0 deletions Graphs/The-Kingdom’s-Gold-Vault/python-code.py
Original file line number Diff line number Diff line change
@@ -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()