LeetCode 11.

Tags:

Question

Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, 
find two numbers such that they add up to a specific target number. 
Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.

Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.

The tests are generated such that there is exactly one solution. You may not use the same element twice.

Your solution must use only constant extra space.

Intuition

The answer is the maximum area of the container (width * Min(height[left], height[right]))

The container must have two sides (left & right) so I try two pointers first.

Approach

The problem is: When should the left pointer move right and the right pointer move left?

Here’s the rule:

  • Compare the Area[i+1, j] and Area[i, j-1]. The width of them are equal so we should focus on their heights.
  • Assume height[i], height[j], height[i+1], height[j-1] which 0 <= i < j < n
  • If height[i] < height[j], Area[i,j] > Area[i,j-1]
  • Otherwise, Area[i,j] > Area[i+1,j]

Use the example to exmaplify:

  • height = [1,8,6,2,5,4,8,3,7]
  • i=0, j=8, height[0] < height[8]
  • Area[0, 8] = Min(height[0], height[8]) * 8 = 1 * 8 = 8
  • Compare two sub-situations: Area[0,7] & Area[1,8]:
    • Area[0,7] = Min(1, 3) * 7 = 7 (Maintaining the smaller height (height[0]) cause the result must be smaller than previous result)
    • Area[1,8] = Min(8, 7) * 7 = 49 (The answer will be in this case)

Complexity

  • Time complexity: O(n)

  • Space complexity: O(1)

Code

class Solution {
    public int maxArea(int[] height) {
        if (height.length == 1) return 0;
        int left = 0, right = height.length - 1;
        int max = -1;

        while (left < right) {
            max = Math.max(max, Math.min(height[left], height[right])*(right-left));
            if (height[left] < height[right]) {
                left++;
            }else{
                right--;
            }
        }
        return max;
    }
}

Check out the description of this problem at LC 11.