Skip to content

Commit ec58da9

Browse files
authored
Added tasks 53-104
1 parent 868f016 commit ec58da9

File tree

20 files changed

+1563
-0
lines changed

20 files changed

+1563
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
53\. Maximum Subarray
2+
3+
Easy
4+
5+
Given an integer array `nums`, find the contiguous subarray (containing at least one number) which has the largest sum and return _its sum_.
6+
7+
A **subarray** is a **contiguous** part of an array.
8+
9+
**Example 1:**
10+
11+
**Input:** nums = [-2,1,-3,4,-1,2,1,-5,4]
12+
13+
**Output:** 6
14+
15+
**Explanation:** [4,-1,2,1] has the largest sum = 6.
16+
17+
**Example 2:**
18+
19+
**Input:** nums = [1]
20+
21+
**Output:** 1
22+
23+
**Example 3:**
24+
25+
**Input:** nums = [5,4,-1,7,8]
26+
27+
**Output:** 23
28+
29+
**Constraints:**
30+
31+
* <code>1 <= nums.length <= 10<sup>5</sup></code>
32+
* <code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code>
33+
34+
**Follow up:** If you have figured out the `O(n)` solution, try coding another solution using the **divide and conquer** approach, which is more subtle.
35+
36+
To solve the Maximum Subarray problem, we can use the Kadane's algorithm, which efficiently finds the maximum subarray sum in linear time. Here are the steps to solve the task:
37+
38+
1. **Initialize Variables:**
39+
- Initialize two variables `max_sum` and `current_sum` to keep track of the maximum sum found so far and the sum of the current subarray, respectively.
40+
- Set `max_sum` and `current_sum` to the value of the first element in the array `nums`.
41+
42+
2. **Iterate Through the Array:**
43+
- Start iterating through the array `nums` from the second element (index 1).
44+
- For each element `num` in `nums`, do the following:
45+
- Update `current_sum` to be the maximum of either `num` or `current_sum + num`. This step ensures that we consider either starting a new subarray or extending the current subarray.
46+
- Update `max_sum` to be the maximum of either `max_sum` or `current_sum`. This step ensures that we keep track of the maximum subarray sum found so far.
47+
48+
3. **Return the Result:**
49+
- After iterating through the entire array, `max_sum` will contain the maximum subarray sum.
50+
- Return `max_sum` as the result.
51+
52+
### Python Implementation:
53+
54+
```python
55+
class Solution:
56+
def maxSubArray(self, nums: List[int]) -> int:
57+
# Initialize variables
58+
max_sum = current_sum = nums[0]
59+
60+
# Iterate through the array
61+
for num in nums[1:]:
62+
current_sum = max(num, current_sum + num)
63+
max_sum = max(max_sum, current_sum)
64+
65+
return max_sum
66+
67+
# Example Usage:
68+
solution = Solution()
69+
nums1 = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
70+
print(solution.maxSubArray(nums1)) # Output: 6
71+
72+
nums2 = [1]
73+
print(solution.maxSubArray(nums2)) # Output: 1
74+
75+
nums3 = [5, 4, -1, 7, 8]
76+
print(solution.maxSubArray(nums3)) # Output: 23
77+
```
78+
79+
This algorithm has a time complexity of O(n), where n is the length of the input array `nums`. Therefore, it efficiently finds the maximum subarray sum.

g0001_0100/s0055_jump_game/readme.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
55\. Jump Game
2+
3+
Medium
4+
5+
You are given an integer array `nums`. You are initially positioned at the array's **first index**, and each element in the array represents your maximum jump length at that position.
6+
7+
Return `true` _if you can reach the last index, or_ `false` _otherwise_.
8+
9+
**Example 1:**
10+
11+
**Input:** nums = [2,3,1,1,4]
12+
13+
**Output:** true
14+
15+
**Explanation:** Jump 1 step from index 0 to 1, then 3 steps to the last index.
16+
17+
**Example 2:**
18+
19+
**Input:** nums = [3,2,1,0,4]
20+
21+
**Output:** false
22+
23+
**Explanation:** You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
24+
25+
**Constraints:**
26+
27+
* <code>1 <= nums.length <= 10<sup>4</sup></code>
28+
* <code>0 <= nums[i] <= 10<sup>5</sup></code>
29+
30+
To solve the "Jump Game" problem, you can follow these steps:
31+
32+
1. **Initialize Variables:** Start by initializing a variable `max_reach` to store the maximum reachable index. Initially, set `max_reach` to `0`, as you are at the first index.
33+
34+
2. **Iterate through the Array:** Traverse through the array `nums` starting from index `0` to `n-1`, where `n` is the length of the array.
35+
36+
3. **Update Maximum Reach:** At each index `i`, update `max_reach` to be the maximum of `max_reach` and `i + nums[i]`. This indicates the farthest index you can reach from the current position `i`.
37+
38+
4. **Check for End Reachability:** While traversing the array, if at any point `max_reach` becomes greater than or equal to the last index (i.e., `n - 1`), return `True`, indicating that you can reach the end of the array.
39+
40+
5. **Handle Zero Reach:** If the current index `i` is greater than `max_reach`, it means you cannot progress further, and thus, return `False`.
41+
42+
6. **Return Result:** After iterating through the entire array, if you haven't reached the end of the array, return `False`, as you cannot reach the last index.
43+
44+
Here's a Python function implementing the above steps:
45+
46+
```python
47+
from typing import List
48+
49+
class Solution:
50+
def canJump(self, nums: List[int]) -> bool:
51+
max_reach = 0
52+
n = len(nums)
53+
54+
for i in range(n):
55+
if i > max_reach:
56+
return False
57+
max_reach = max(max_reach, i + nums[i])
58+
if max_reach >= n - 1:
59+
return True
60+
61+
return False
62+
63+
# Example usage:
64+
nums1 = [2, 3, 1, 1, 4]
65+
nums2 = [3, 2, 1, 0, 4]
66+
67+
sol = Solution()
68+
print(sol.canJump(nums1)) # Output: True
69+
print(sol.canJump(nums2)) # Output: False
70+
```
71+
72+
You can then test this function with different input arrays to verify its correctness.
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
56\. Merge Intervals
2+
3+
Medium
4+
5+
Given an array of `intervals` where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_.
6+
7+
**Example 1:**
8+
9+
**Input:** intervals = [[1,3],[2,6],[8,10],[15,18]]
10+
11+
**Output:** [[1,6],[8,10],[15,18]]
12+
13+
**Explanation:** Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
14+
15+
**Example 2:**
16+
17+
**Input:** intervals = [[1,4],[4,5]]
18+
19+
**Output:** [[1,5]]
20+
21+
**Explanation:** Intervals [1,4] and [4,5] are considered overlapping.
22+
23+
**Constraints:**
24+
25+
* <code>1 <= intervals.length <= 10<sup>4</sup></code>
26+
* `intervals[i].length == 2`
27+
* <code>0 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>4</sup></code>
28+
29+
Here are the steps to solve the task using the `Solution` class:
30+
31+
1. Define the `Solution` class with a method named `merge` that takes in a list of intervals.
32+
2. Inside the `merge` method, sort the intervals based on their start times.
33+
3. Initialize an empty list called `merged_intervals` to store the merged intervals.
34+
4. Iterate through the sorted intervals.
35+
5. For each interval, if the `merged_intervals` list is empty or if the current interval's start time is greater than the end time of the last interval in the `merged_intervals` list, append the current interval to `merged_intervals`.
36+
6. Otherwise, merge the current interval with the last interval in the `merged_intervals` list by updating the end time of the last interval if the current interval's end time is greater.
37+
7. After iterating through all intervals, return the `merged_intervals` list.
38+
39+
Here's the implementation:
40+
41+
```python
42+
from typing import List
43+
44+
class Solution:
45+
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
46+
intervals.sort(key=lambda x: x[0])
47+
merged_intervals = []
48+
49+
for interval in intervals:
50+
if not merged_intervals or interval[0] > merged_intervals[-1][1]:
51+
merged_intervals.append(interval)
52+
else:
53+
merged_intervals[-1][1] = max(merged_intervals[-1][1], interval[1])
54+
55+
return merged_intervals
56+
57+
# Example usage:
58+
intervals1 = [[1, 3], [2, 6], [8, 10], [15, 18]]
59+
intervals2 = [[1, 4], [4, 5]]
60+
61+
sol = Solution()
62+
print(sol.merge(intervals1)) # Output: [[1, 6], [8, 10], [15, 18]]
63+
print(sol.merge(intervals2)) # Output: [[1, 5]]
64+
```
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
62\. Unique Paths
2+
3+
Medium
4+
5+
A robot is located at the top-left corner of a `m x n` grid (marked 'Start' in the diagram below).
6+
7+
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
8+
9+
How many possible unique paths are there?
10+
11+
**Example 1:**
12+
13+
![](https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png)
14+
15+
**Input:** m = 3, n = 7
16+
17+
**Output:** 28
18+
19+
**Example 2:**
20+
21+
**Input:** m = 3, n = 2
22+
23+
**Output:** 3
24+
25+
**Explanation:**
26+
27+
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
28+
1. Right -> Down -> Down
29+
2. Down -> Down -> Right
30+
3. Down -> Right -> Down
31+
32+
**Example 3:**
33+
34+
**Input:** m = 7, n = 3
35+
36+
**Output:** 28
37+
38+
**Example 4:**
39+
40+
**Input:** m = 3, n = 3
41+
42+
**Output:** 6
43+
44+
**Constraints:**
45+
46+
* `1 <= m, n <= 100`
47+
* It's guaranteed that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.
48+
49+
To solve this task using Python with a `Solution` class, you can follow these steps:
50+
51+
1. Define a class named `Solution`.
52+
2. Inside the class, define a method named `uniquePaths` that takes `m` and `n` as input parameters.
53+
3. Implement the logic to calculate the number of unique paths using dynamic programming.
54+
4. Create a grid of size `m x n` to store the number of unique paths to each cell.
55+
5. Initialize the first row and first column of the grid to 1, as there is only one way to reach any cell in the first row or column.
56+
6. Iterate through the grid and calculate the number of unique paths to each cell using the formula `grid[i][j] = grid[i-1][j] + grid[i][j-1]`.
57+
7. Return the number of unique paths to the bottom-right corner of the grid (`grid[m-1][n-1]`).
58+
59+
Here's the implementation:
60+
61+
```python
62+
class Solution:
63+
def uniquePaths(self, m: int, n: int) -> int:
64+
# Create a grid to store the number of unique paths to each cell
65+
grid = [[0] * n for _ in range(m)]
66+
67+
# Initialize the first row and first column to 1
68+
for i in range(m):
69+
grid[i][0] = 1
70+
for j in range(n):
71+
grid[0][j] = 1
72+
73+
# Calculate the number of unique paths to each cell
74+
for i in range(1, m):
75+
for j in range(1, n):
76+
grid[i][j] = grid[i-1][j] + grid[i][j-1]
77+
78+
# Return the number of unique paths to the bottom-right corner
79+
return grid[m-1][n-1]
80+
81+
# Example usage:
82+
solution = Solution()
83+
print(solution.uniquePaths(3, 7)) # Output: 28
84+
print(solution.uniquePaths(3, 2)) # Output: 3
85+
print(solution.uniquePaths(7, 3)) # Output: 28
86+
print(solution.uniquePaths(3, 3)) # Output: 6
87+
```
88+
89+
This implementation uses dynamic programming to efficiently calculate the number of unique paths. It iterates through the grid only once, so the time complexity is O(m * n), where m is the number of rows and n is the number of columns.
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
64\. Minimum Path Sum
2+
3+
Medium
4+
5+
Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
6+
7+
**Note:** You can only move either down or right at any point in time.
8+
9+
**Example 1:**
10+
11+
![](https://assets.leetcode.com/uploads/2020/11/05/minpath.jpg)
12+
13+
**Input:** grid = [[1,3,1],[1,5,1],[4,2,1]]
14+
15+
**Output:** 7
16+
17+
**Explanation:** Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
18+
19+
**Example 2:**
20+
21+
**Input:** grid = [[1,2,3],[4,5,6]]
22+
23+
**Output:** 12
24+
25+
**Constraints:**
26+
27+
* `m == grid.length`
28+
* `n == grid[i].length`
29+
* `1 <= m, n <= 200`
30+
* `0 <= grid[i][j] <= 100`
31+
32+
To solve this task using Python with a `Solution` class, you can follow these steps:
33+
34+
1. Define a class named `Solution`.
35+
2. Inside the class, define a method named `minPathSum` that takes `grid` as an input parameter.
36+
3. Implement the logic to calculate the minimum path sum using dynamic programming.
37+
4. Create a 2D grid of size `m x n` to store the minimum path sum to each cell.
38+
5. Initialize the first row and first column of the grid with cumulative sums.
39+
6. Iterate through the grid starting from the second row and second column.
40+
7. For each cell, update its value to the minimum of the values to its left and above plus the current cell's value.
41+
8. Return the value in the bottom-right cell of the grid, which represents the minimum path sum.
42+
43+
Here's the implementation:
44+
45+
```python
46+
class Solution:
47+
def minPathSum(self, grid: List[List[int]]) -> int:
48+
# Get the dimensions of the grid
49+
m, n = len(grid), len(grid[0])
50+
51+
# Create a grid to store the minimum path sum to each cell
52+
dp = [[0] * n for _ in range(m)]
53+
54+
# Initialize the first row and first column
55+
dp[0][0] = grid[0][0]
56+
for i in range(1, m):
57+
dp[i][0] = dp[i-1][0] + grid[i][0]
58+
for j in range(1, n):
59+
dp[0][j] = dp[0][j-1] + grid[0][j]
60+
61+
# Calculate the minimum path sum for each cell
62+
for i in range(1, m):
63+
for j in range(1, n):
64+
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
65+
66+
# Return the minimum path sum in the bottom-right cell
67+
return dp[m-1][n-1]
68+
69+
# Example usage:
70+
solution = Solution()
71+
print(solution.minPathSum([[1,3,1],[1,5,1],[4,2,1]])) # Output: 7
72+
print(solution.minPathSum([[1,2,3],[4,5,6]])) # Output: 12
73+
```
74+
75+
This implementation uses dynamic programming to efficiently calculate the minimum path sum. It iterates through the grid only once, so the time complexity is O(m * n), where m is the number of rows and n is the number of columns.

0 commit comments

Comments
 (0)