Skip to content

Commit 641cc69

Browse files
authored
Create 04 - Bottom-Up | DP | Approach.cpp
1 parent 3896799 commit 641cc69

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class Solution {
2+
public:
3+
// Function to solve the problem using dynamic programming with space optimization
4+
int solve(vector<int>& obstacles) {
5+
int n = obstacles.size() - 1; // Get the last position in the obstacles array
6+
7+
// Create two vectors to represent the current and next state of the dp table
8+
// curr[lane] represents the minimum jumps required from the current position in the lane.
9+
// next[lane] represents the minimum jumps required from the next position in the lane.
10+
vector<int> curr(4, INT_MAX); // Initialize the current state with large values (INT_MAX).
11+
vector<int> next(4, INT_MAX); // Initialize the next state with large values (INT_MAX).
12+
13+
// At the last position (n), no jumps are needed, so we set all lanes to 0
14+
next[0] = 0;
15+
next[1] = 0;
16+
next[2] = 0;
17+
next[3] = 0;
18+
19+
// Iterate from the second-last position to the start of the array
20+
for (int pos = n - 1; pos >= 0; pos--) {
21+
// Try all 3 lanes (1, 2, 3) for each position
22+
for (int lane = 1; lane <= 3; lane++) {
23+
24+
// If the next position is not blocked by the current lane, no jump is needed
25+
if (obstacles[pos + 1] != lane) {
26+
curr[lane] = next[lane]; // Carry over the result from the next position
27+
} else {
28+
// If the next position is blocked, we need to jump to a different lane
29+
int ans = INT_MAX; // Initialize the answer to a large value (to minimize later)
30+
31+
// Try all 3 possible lanes (1, 2, 3) to find the best jump option
32+
for (int i = 1; i <= 3; i++) {
33+
// If the current lane is not the lane we're trying to jump to, and the lane is not blocked
34+
if (lane != i && obstacles[pos] != i) {
35+
// Add 1 for the jump and update the answer with the minimum jumps required
36+
ans = min(ans, 1 + next[i]);
37+
}
38+
}
39+
40+
// Store the minimum jumps required for this position and lane in the curr array
41+
curr[lane] = ans;
42+
}
43+
}
44+
45+
// After processing all lanes for this position, move the next state to curr
46+
next = curr;
47+
}
48+
49+
// Return the minimum side jumps required starting from position 0 with lane 2.
50+
// We also consider the case where we might need one jump to lane 1 or lane 3.
51+
return min({curr[2], curr[1] + 1, curr[3] + 1});
52+
}
53+
54+
// Main function to return the minimum number of side jumps
55+
int minSideJumps(vector<int>& obstacles) {
56+
return solve(obstacles); // Call the solve function to get the result
57+
}
58+
};

0 commit comments

Comments
 (0)