Microsoft Online Assessment (OA) - Largest K such that both K and -K exist in array
Given an array A
of N
integers, return the largest integer K > 0
such that both values K
and -K
exist in the array A
.
If there is no such integer, the function should return 0
.
Example 1:
Input:[3, 2, -2, 5, -3]
Output: 3
Example 2:
Input:[1, 2, 3, -4]
Output: 0
Try it yourself
Implementation
1from typing import List
2
3def largest_k(nums: List[int]) -> int:
4 result = 0
5 for i in nums:
6 if i < 0 and -i in nums:
7 result = max(result, -i)
8 return result
9
10if __name__ == "__main__":
11 nums = [int(x) for x in input().split()]
12 res = largest_k(nums)
13 print(res)
14
1import java.util.Arrays;
2import java.util.HashSet;
3import java.util.List;
4import java.util.Scanner;
5import java.util.stream.Collectors;
6
7class Solution {
8 public static int largestK(List<Integer> nums) {
9 HashSet<Integer> set = new HashSet<>();
10 int curMax = 0;
11 for (int a : nums) {
12 if (set.contains(-a))
13 curMax = Math.max(curMax, Math.abs(a));
14 else
15 set.add(a);
16 }
17 return curMax;
18 }
19
20 public static List<String> splitWords(String s) {
21 return s.isEmpty() ? List.of() : Arrays.asList(s.split(" "));
22 }
23
24 public static void main(String[] args) {
25 Scanner scanner = new Scanner(System.in);
26 List<Integer> nums = splitWords(scanner.nextLine()).stream().map(Integer::parseInt).collect(Collectors.toList());
27 scanner.close();
28 int res = largestK(nums);
29 System.out.println(res);
30 }
31}
32
1"use strict";
2
3function largestK(nums) {
4 let maxValue = 0;
5 const size = nums.length;
6 for (let i = 0; i <= size; i++) {
7 if (Math.abs(nums[i]) > maxValue && nums.indexOf(-nums[i]) !== -1) {
8 maxValue = nums[i];
9 }
10 }
11 return maxValue;
12}
13
14function splitWords(s) {
15 return s === "" ? [] : s.split(" ");
16}
17
18function* main() {
19 const nums = splitWords(yield).map((v) => parseInt(v));
20 const res = largestK(nums);
21 console.log(res);
22}
23
24class EOFError extends Error {}
25{
26 const gen = main();
27 const next = (line) => gen.next(line).done && process.exit();
28 let buf = "";
29 next();
30 process.stdin.setEncoding("utf8");
31 process.stdin.on("data", (data) => {
32 const lines = (buf + data).split("\n");
33 buf = lines.pop();
34 lines.forEach(next);
35 });
36 process.stdin.on("end", () => {
37 buf && next(buf);
38 gen.throw(new EOFError());
39 });
40}
41