1. 3Sum Closest:
How to solve:
Sort the array. This helps us efficiently narrow down the combinations.
Use a for loop to fix the first number, then use the two-pointer technique to find the other two numbers.
Start the two pointers: one at the beginning of the remaining part of the array and one at the end.
Calculate the sum of the three numbers.
If the sum is closer to the target than the current closest sum, update the closest sum.
Adjust the pointers:
- If the sum is less than the target, move the left pointer right to increase the sum.
- If the sum is greater than the target, move the right pointer left to decrease the sum.
- Continue this process until you've checked all possibilities.
2. Container With Most Water:
Let's tackle the problem by applying the two-pointer technique as follows:
Assume that one pointer is located at the start of the array, while the other is located at the end of the array.
The area between the two lines can be determined by the following formula.
Area = min(height[left], height[right]) * (right left)
If the height of the left line is less than that of the right line height, then the left pointer has to be shifted to the right.
If the right line height is lesser than the height of the left line height, then the right pointer will shift and move towards the left.
While adjusting the pointers in your mind, you have to remember how much was the largest area formed because of these adjustments.
Top comments (0)