Microsoft Online Assessment (OA) - Largest K such that both K and -K exist in array
Given an array A
of N
integers, returns the largest integer K > 0
such that both values K
and -K
exist in 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
1function largestK(nums) {
2 let maxValue = 0;
3 const size = nums.length;
4 for (let i = 0; i <= size; i++) {
5 if (Math.abs(nums[i]) > maxValue && nums.indexOf(-nums[i]) !== -1) {
6 maxValue = nums[i];
7 }
8 }
9 return maxValue;
10}
11
12function splitWords(s) {
13 return s == "" ? [] : s.split(' ');
14}
15
16function* main() {
17 const nums = splitWords(yield).map((v) => parseInt(v));
18 const res = largestK(nums);
19 console.log(res);
20}
21
22class EOFError extends Error {}
23{
24 const gen = main();
25 const next = (line) => gen.next(line).done && process.exit();
26 let buf = '';
27 next();
28 process.stdin.setEncoding('utf8');
29 process.stdin.on('data', (data) => {
30 const lines = (buf + data).split('\n');
31 buf = lines.pop();
32 lines.forEach(next);
33 });
34 process.stdin.on('end', () => {
35 buf && next(buf);
36 gen.throw(new EOFError());
37 });
38}
39
Got a question?ย Ask the Teaching Assistantย anything you don't understand.
Still not clear? Ask in the Forum, ย Discordย orย Submitย the part you don't understand to our editors.