Skip to content

Commit 73b2c7a

Browse files
committed
📝 [198]
1 parent 5dc5bc0 commit 73b2c7a

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

198/o_solution.js

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
const rob = (nums) => {
6+
let rob1 = 0, rob2 = 0;
7+
8+
for (let i = 0; i < nums.length; i++) {
9+
let tmp = Math.max(rob1 + nums[i], rob2);
10+
rob1 = rob2;
11+
rob2 = tmp;
12+
}
13+
14+
console.log("rob2")
15+
console.log(rob2)
16+
17+
return rob2;
18+
};
19+
20+
// rob([1, 2])
21+
// rob([2, 1, 1, 2])
22+
// rob([2, 3, 1, 2, 1, 1, 2])
23+
rob([2, 7, 9, 3, 1])
24+
// rob([1, 2, 3, 1])
25+
// rob([1, 2, 3])
26+
// rob([0])

198/solution.js

+16
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,19 @@ const rob = (nums) => {
1616

1717
return Math.max(...tmpList);
1818
};
19+
20+
/**
21+
22+
The time and space complexities of the provided code are as follows:
23+
24+
Time Complexity: O(n)
25+
The code uses a loop to iterate over the input array nums. For each element, it performs some operations such as finding the maximum value in a slice of tmpList and pushing values into tmpList. The time complexity of finding the maximum value in a slice is O(k), where k is the length of the slice. Since the size of the slice (i - 2 + 1) is limited to a constant value (3), the maximum value operation can be considered constant time.
26+
27+
Therefore, the dominant factor in the time complexity is the loop that iterates over nums. Hence, the time complexity of the code is O(n), where n is the length of the input array nums.
28+
29+
Space Complexity: O(n)
30+
The code uses an additional array called tmpList to store intermediate results. The size of tmpList grows with the input size (nums). Therefore, the space complexity of the code is O(n), where n is the length of the input array nums.
31+
32+
In summary, the time complexity of the code is O(n), and the space complexity is also O(n).
33+
34+
*/

0 commit comments

Comments
 (0)