Skip to content

Commit 48dc52e

Browse files
committed
Add solution #1443
1 parent 50ac15c commit 48dc52e

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,7 @@
248248
1431|[Kids With the Greatest Number of Candies](./1431-kids-with-the-greatest-number-of-candies.js)|Easy|
249249
1436|[Destination City](./1436-destination-city.js)|Easy|
250250
1437|[Check If All 1's Are at Least Length K Places Away](./1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy|
251+
1443|[Minimum Time to Collect All Apples in a Tree](./1443-minimum-time-to-collect-all-apples-in-a-tree.js)|Medium|
251252
1446|[Consecutive Characters](./1446-consecutive-characters.js)|Easy|
252253
1447|[Simplified Fractions](./1447-simplified-fractions.js)|Medium|
253254
1450|[Number of Students Doing Homework at a Given Time](./1450-number-of-students-doing-homework-at-a-given-time.js)|Easy|
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 1443. Minimum Time to Collect All Apples in a Tree
3+
* https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/
4+
* Difficulty: Medium
5+
*
6+
* Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples
7+
* in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time
8+
* in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming
9+
* back to this vertex.
10+
*
11+
* The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means
12+
* that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array
13+
* hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not
14+
* have any apple.
15+
*/
16+
17+
/**
18+
* @param {number} n
19+
* @param {number[][]} edges
20+
* @param {boolean[]} hasApple
21+
* @return {number}
22+
*/
23+
var minTime = function(n, edges, hasApple) {
24+
const map = new Map();
25+
const seen = new Set();
26+
let time = 0;
27+
28+
edges.forEach(([value, key]) => map.set(key, value));
29+
for (let i = n - 1; i >= 0; i--) {
30+
if (hasApple[i]) {
31+
dfs(i);
32+
}
33+
}
34+
35+
function dfs(key) {
36+
if (key === 0 || seen.has(key)) return;
37+
seen.add(key);
38+
time += 2;
39+
dfs(map.get(key));
40+
}
41+
42+
return time;
43+
};

0 commit comments

Comments
 (0)