3876. Construct Uniform Parity Array II
/**
* Problem: LeetCode 3876 - Construct Uniform Parity Array II
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public boolean uniformArray(int[] nums1) {
return canMakeAll(nums1, 0) || canMakeAll(nums1, 1);
}
private boolean canMakeAll(int[] nums, int targetParity) {
int[] globalMin = {Integer.MAX_VALUE, Integer.MAX_VALUE};
for (int x : nums) {
globalMin[x % 2] = Math.min(globalMin[x % 2], x);
}
for (int x : nums) {
int curParity = x % 2;
if (curParity == targetParity) {
continue;
}
int neededJParity = (targetParity + curParity) % 2;
if (globalMin[neededJParity] >= x) {
return false; // no valid strictly smaller j exists
}
}
return true;
}
}
"""
Problem: LeetCode 3876 - Construct Uniform Parity Array II
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
from typing import List
class Solution:
def uniformArray(self, nums1: List[int]) -> bool:
def can_make_all(target_parity: int) -> bool:
global_min = [float('inf'), float('inf')]
for x in nums1:
global_min[x % 2] = min(global_min[x % 2], x)
for x in nums1:
cur_parity = x % 2
if cur_parity == target_parity:
continue
needed_j_parity = (target_parity + cur_parity) % 2
if global_min[needed_j_parity] >= x:
return False
return True
return can_make_all(0) or can_make_all(1)
/**
* Problem: LeetCode 3876 - Construct Uniform Parity Array II
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
/**
* Problem: LeetCode 3876 - Construct Uniform Parity Array II
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
bool uniformArray(vector<int>& nums1) {
return canMakeAll(nums1, 0) || canMakeAll(nums1, 1);
}
private:
bool canMakeAll(const vector<int>& nums, int targetParity) {
int globalMin[2] = {INT_MAX, INT_MAX};
for (int x : nums) {
globalMin[x % 2] = min(globalMin[x % 2], x);
}
for (int x : nums) {
int curParity = x % 2;
if (curParity == targetParity) {
continue;
}
int neededJParity = (targetParity + curParity) % 2;
if (globalMin[neededJParity] >= x) {
return false;
}
}
return true;
}
};
/**
* Problem: LeetCode 3876 - Construct Uniform Parity Array II
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
var uniformArray = function(nums1) {
function canMakeAll(targetParity) {
const globalMin = [Infinity, Infinity];
for (const x of nums1) {
globalMin[x % 2] = Math.min(globalMin[x % 2], x);
}
for (const x of nums1) {
const curParity = x % 2;
if (curParity === targetParity) {
continue;
}
const neededJParity = (targetParity + curParity) % 2;
if (globalMin[neededJParity] >= x) {
return false;
}
}
return true;
}
return canMakeAll(0) || canMakeAll(1);
};