Untitled

 avatar
unknown
plain_text
12 days ago
1.5 kB
3
Indexable
import java.util.*;

public class ThreeSumClosest {
    public static int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums); // Step 1: Sort the array
        int closestSum = Integer.MAX_VALUE / 2; // Initialize with a large value
        
        for (int i = 0; i < nums.length - 2; i++) {
            int left = i + 1, right = nums.length - 1;

            while (left < right) {
                int currentSum = nums[i] + nums[left] + nums[right];
                
                // Update the closest sum if needed
                if (Math.abs(currentSum - target) < Math.abs(closestSum - target)) {
                    closestSum = currentSum;
                }
                
                if (currentSum < target) {
                    left++; // Increase the sum
                } else if (currentSum > target) {
                    right--; // Decrease the sum
                } else {
                    return currentSum; // Exact match found
                }
            }
        }
        return closestSum;
    }

    public static void main(String[] args) {
        int[] nums1 = {-1, 2, 1, -4};
        int target1 = 1;
        System.out.println("Closest Sum: " + threeSumClosest(nums1, target1)); // Output: 2

        int[] nums2 = {0, 0, 0};
        int target2 = 1;
        System.out.println("Closest Sum: " + threeSumClosest(nums2, target2)); // Output: 0
    }
}
Leave a Comment