💯✅Runtime 5 ms Beats 84.11% of users with Java||💯✅Memory 44.88 MB Beats 43.00% of users with Java
Intuition\n Describe your first thoughts on how to solve this problem. \n- The given code aims to find the maximum value of k in an array of integers such that 
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- The given code aims to find the maximum value of k in an array of integers such that both k and -k exist in the array.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- The findMaxK method first checks for edge cases where the input array is null or empty, returning -1 in such cases.\n- It then sorts the input array in ascending order.\n\n- It iterates through the array, looking for negative values. For each negative value, it calculates its positive counterpart and searches for it in the array using the search method.\n- \n- The search method performs a binary search to find the index of the positive counterpart in the sorted array.\n- \n- If a positive counterpart is found, it returns the actual value of k; otherwise, it returns -1.\n# Complexity\n- Time complexity:O(n log n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport java.util.Arrays;\n\nclass Solution {\n    public int findMaxK(int[] nums) {\n        if (nums == null || nums.length == 0) {\n            return -1; // Handle edge case of null or empty array\n        }\n\n        Arrays.sort(nums);\n\n        for (int i = 0; i < nums.length && nums[i] < 0; i++) {\n            int val = -nums[i];\n            int index = search(nums, val);\n            if (index >= 0) {\n                return val; // Return the actual value of k\n            }\n        }\n\n        return -1; // Return -1 if no matching positive value is found\n    }\n\n    private static int search(int[] arr, int t) {\n        int s = 0;\n        int e = arr.length - 1;\n\n        while (s <= e) {\n            int m = s + (e - s) / 2;\n            if (arr[m] == t) {\n                return m; // Return the index of the found element\n            } else if (arr[m] < t) {\n                s = m + 1;\n            } else {\n                e = m - 1;\n            }\n        }\n        return -1; // Return -1 if the element is not found\n    }\n}\n```\n![upvote.png](https://assets.leetcode.com/users/images/531e2611-2d66-4d79-b1a2-2834bdc0419a_1715127895.4791088.png)\n
['Array', 'Java']