- get the sum of an array of integers and return [-1,0,1] is the sum is negative, 0, positive.
[1,-2,-3,5] = 30 return 1
[1,-2,3,5] = -30 return -1
[1,-2,3,0] = 0 return 0
sum = nums[0]
sum *= nums[1..n]
return (sum > 0) ? 1 : (sum < 0) ? -1 : 0;
- https://stackoverflow.com/questions/23113268/monotonic-pair-codility
optimize the solution.
given an array of int [2,6,2,6,1] return the largest difference in index of a number's reoccurence in the array.
A[0] = 2 -> 0,2 -> 0-0, 2-0 = 2
A[1] = 6 -> 1,3,6 -> 1-1, 3-1, 6 - 1 = 5
A[2] = 2 -> 0,2
A[3] = 6 -> 1,3,6
A[4] = 1 -> 4 -> 4-4 = 0
A[5] = 6 -> 1,3,6
return 5.
you are given the answer in O(n^2) time that use 2 for loops and an if(nums[i] == nums[j]) result = Math.max(result, j - i);
we only care about the largest index of a number in the array.
I store the numbers in a map and update the index as value
iterate through the nums array once and lookup the map.
result = Math.max(result, map.get(nums[i] - i))
This should be O(n) time and O(n) space
- given an integer, remove a number 5 from it and return the largest value.
15985 -> 1985 or 1598, return 1958
-15958 -> -1958 or -1598, return -1598
convert number to stringbuilder
if(n > 0)
get the first index of 5 and delete from stringbuilder
else if(n < 0)
get the last index of 5 and delete from stringbuilder