### Selection Sort Algorithm

It is one of a simple algorithm to study for a beginner to understanding sorting…

September 13, 2019

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

```
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
```

The obvious brute force algorithm. The key is to get the closest. You need to compare

`Math.abs(target - calculated_sum)`

Lets look at the optimized solution.

- Sort the array
- Have left and right pointers.
- Keep calculating sum of three values.
- Compare absolute value of difference between targetSum and calculated sum.
- If sum is lesser, need to move left pointer
- else move right pointer.

```
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int l = nums.length;
int minDiff = Integer.MAX_VALUE;
int result = 0;
for (int i=0; i<l; i++) {
int j=i+1;
int k=l-1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum == target) return sum;
else if (sum < target) j++;
else k--;
if (Math.abs(target - sum) < minDiff) {
minDiff = Math.abs(target - sum);
result = sum;
}
}
}
return result;
}
```

It is one of a simple algorithm to study for a beginner to understanding sorting…

Problem Statement You are given a rows x cols matrix grid. Initially, you are…

Problem Statement Roman numerals are represented by seven different symbols: I…

Problem Statement Determine whether an integer is a palindrome. An integer is a…

Problem Statement Given a non-empty array of integers, every element appears…

Problem Statement Say you have an array prices for which the ith element is the…

Introduction Lets assume we have a csv something similar to following: Python…

Introduction In last post, we saw How to read CSV with Headers into Dictionary…

Introduction Power BI is a wonderful tool to give life to your data, by…

Problem Statement You are given an array prices where prices[i] is the price of…

Introduction In this post we will see: How to prepare a docker image for your…

Introduction We have a page, for example a . And, upon submission we would want…