The solution involves verifying that the array length equals the maximum value plus one, then sorting the array and confirmnig that elements form a sequence from 0 to max - 1.
class Solution {
public:
bool isGood(vector<int>& nums) {
int maxVal = 0;
for(auto val : nums){
maxVal = max(maxVal, val);
}
if(maxVal + 1 != nums.size())
return false;
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size() - 2; i++){
if(nums[i] + 1 != nums[i + 1])
return false;
}
return true;
}
};
6926. Sort Vowels in a String - LeetCode
This approach extracts all vowels, sorts them, and replaces the vowels in the original string with the sorted ones.
class Solution {
public:
string sortVowels(string str) {
string vowels = "";
string vowelSet = "aeiouAEIOU";
for(auto ch : str){
if(vowelSet.find(ch) != -1){
vowels += ch;
}
}
sort(vowels.begin(), vowels.end());
int index = 0;
for(int i = 0; i < str.size(); i++){
if(vowelSet.find(str[i]) != -1){
str[i] = vowels[index++];
}
}
return str;
}
};
6931. Maximum Score From Placing Players - LeetCode
This problem uses dynamic programming where transitions are made from the end to the begining. It tracks maximum scores for even and odd numbers separately.
class Solution {
public:
long long maxScore(vector<int>& nums, int penalty) {
long long size = nums.size();
vector<vector<long long>> dp(2, vector<long long>(size, 0));
dp[nums[size - 1] & 1][size - 1] = nums[size - 1];
dp[!(nums[size - 1] & 1)][size - 1] = max(0, nums[size - 1] - penalty);
for(long long i = size - 2; i >= 0; i--){
dp[0][i] = dp[0][i + 1];
dp[1][i] = dp[1][i + 1];
dp[nums[i] & 1][i] += nums[i];
dp[0][i] = max(dp[0][i], dp[1][i] - penalty);
dp[1][i] = max(dp[1][i], dp[0][i] - penalty);
}
return dp[nums[0] & 1][0];
}
};
6922. Number of Ways to Express an Integer as Sum of Powers - LeetCode
This is a classic 0/1 knapsack problem. Each power of a number is treated as an item, and we count how many ways we can fill up to the target number.
class Solution {
public:
int numberOfWays(int target, int power) {
const int MOD = 1e9 + 7;
vector<int> powers(target + 1);
for(int i = 1; i <= target; i++){
long long result = pow(i, power);
powers[i] = result % MOD;
}
vector<int> dp(target + 1);
dp[0] = 1;
for(int i = 1; i <= target; i++){
for(int j = target; j >= powers[i]; j--){
dp[j] = (dp[j] + dp[j - powers[i]]) % MOD;
}
}
return dp[target];
}
};