LeetCode 75

Max Number of K-Sum Pairs

Problem
LC 1679
Topic
Two Pointers
File
official75_LC1679MaxNumberOfKSumPairs.java
Path
pkg5leetcode/official75/official75_LC1679MaxNumberOfKSumPairs.java
Package
pkg5leetcode.official75
Command
java pkg5leetcode/official75/official75_LC1679MaxNumberOfKSumPairs.java
Approach
Hash map counts complements for k-sum pairs.
Complexity
Time O(n), Space O(n)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/official75/official75_LC1679MaxNumberOfKSumPairs.java
1package pkg5leetcode.official75;2 3/*4 * Max Number of K-Sum Pairs | LC 16795 * APPROACH: Hash map counts complements for k-sum pairs.6 * COMPLEXITY: Time O(n), Space O(n)7 */8import java.util.*;9 10public class official75_LC1679MaxNumberOfKSumPairs {11    static int maxOperations(int[] nums, int k) {12        Map<Integer, Integer> freq = new HashMap<>();13        int pairs = 0;14        for (int n : nums) {15            int need = k - n;16            if (freq.getOrDefault(need, 0) > 0) {17                freq.put(need, freq.get(need) - 1);18                pairs++;19            } else {20                freq.put(n, freq.getOrDefault(n, 0) + 1);21            }22        }23        return pairs;24    }25 26    public static void main(String[] args) {27        check(maxOperations(new int[]{1,2,3,4}, 5) == 2, "case1");28        check(maxOperations(new int[]{3,1,3,4,3}, 6) == 1, "case2");29        System.out.println("all tests passed");30    }31 32    static void check(boolean cond, String name) {33        if (!cond) throw new AssertionError("FAILED: " + name);34        System.out.println("  PASS " + name);35    }36}