Find Optimal Weights
two sum close
code
class Solution {
public:
/**
* @param nums an integer array
* @param target an integer
* @return the difference between the sum and the target
*/
int twoSumCloset(vector<int>& nums, int target) {
// Write your code here
int i = 0;
int j = nums.size()-1;
int diff = INT_MAX;
sort(nums.begin(), nums.end());
while(i != j)
{
int total = nums[i] + nums[j];
if(total == target)
{
return 0;
}
diff = min(diff, abs(target-total));
if(total > target)
{
j--;
}
else
{
i++;
}
}
return diff;
}
};