-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximumCountOfPositiveIntegerAndNegativeInteger.ts
More file actions
70 lines (57 loc) · 1.85 KB
/
maximumCountOfPositiveIntegerAndNegativeInteger.ts
File metadata and controls
70 lines (57 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// First Approach - Brute force iteration through nums counting negative and positive numbers,
// returning the Math.max of them. (0ms - Beats 100.00%)
function maximumCount(nums: number[]): number {
let negCount = 0, posCount = 0;
for(const num of nums) {
if(num < 0) {
negCount++;
continue;
}
if(num > 0)
posCount++;
}
return Math.max(negCount, posCount);
};
// Second Approach - Same brute force method as first approach but optimized to stop whenever it finds
// a positive number, calculating the remaining positive numbers based on negative and zeros count. (0ms - Beats 100.00%)
function maximumCount(nums: number[]): number {
let negCount = 0, zeroCount = 0;
for(const num of nums) {
if(num < 0) {
negCount++;
continue;
}
if(num === 0) {
zeroCount++;
continue;
}
break;
}
return Math.max(negCount, nums.length - (zeroCount + negCount));
};
// Third Approach - Binary Search method to find the first 0 and the first 1 to calculate
// the positive and negative count. (0ms - Beats 100.00%)
function maximumCount(nums: number[]): number {
let negCount = binarySearch(nums, 0);
let posCount = nums.length - binarySearch(nums, 1);
return Math.max(negCount, posCount);
};
function binarySearch(nums: number[], target: number) {
let left = 0, right = nums.length - 1, result = nums.length;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if(nums[mid] < target) {
left = mid + 1;
} else {
result = mid;
right = mid - 1;
}
}
return result;
};
const case1 = maximumCount([-2,-1,-1,1,2,3]);
const case2 = maximumCount([-3,-2,-1,0,0,1,2]);
const case3 = maximumCount([5,20,66,1314]);
console.log(`case1: ${case1} // ${case1 === 3}`);
console.log(`case2: ${case2} // ${case2 === 3}`);
console.log(`case3: ${case3} // ${case3 === 4}`);