# Two Sum II - Input array is sorted

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted

## Tuning

Think you are cooking a soup, you need to add salt when taste light or add water if salty.

However, there are two factors.

`x + y > target`

- decrease x
- decrease y

`x + y < target`

- increase x
- increase y

make `x`

the minimum and `y`

the maximum, then only one way to solve the problem.

`x + y > target`

~~decrease x~~- decrease y

`x + y < target`

- increase x
~~increase y~~

code might be like

```
x = first
y = last
while num[x] + num[y] != target
if num[x] + num[y] > target
y = y - 1
if num[x] + num[y] < target
x = x + 1
```

Notes:

Q: Why not `x--`

when `num[x] + num[y] > target`

?

A: value of `x - 1`

and `y`

had already tested.

### Source code *Read on Github*

```
1 public class Solution {
2 public int[] twoSum(int[] numbers, int target) {
3
4 int i = 0;
5 int j = numbers.length - 1;
6
7
8 while(i < j){
9 if (numbers[i] + numbers[j] > target){
10 j--;
11 }else if(numbers[i] + numbers[j] < target){
12 i++;
13 }else { // ==
14 return new int[]{i + 1, j + 1};
15 }
16 }
17
18 throw new RuntimeException();
19 }
20 }
```