class Solution {
public int arrayPairSum(int[] nums) {
int sum = 0;
Arrays.sort(nums);
for(int i = 0; i < nums.length; i++) {
if(i % 2 == 0) {
sum += nums[i];
}
}
return sum;
}
}
455. Assign Cookies
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int count = 0;
int lg = g.length, ls = s.length;
int i = 0;
int j = 0;
while(i < lg && j < ls) {
if(s[j] >= g[i]) {
count++;
i++;
}
j++;
}
return count;
}
}
575. Distribute Candies
class Solution {
public int distributeCandies(int[] candyType) {
int type = 1;
int len = candyType.length / 2;
Arrays.sort(candyType);
for(int i = 0; i < candyType.length - 1; i ++) {
if(candyType[i] != candyType[i + 1]) {
type++;
}
}
return len > type ? type : len;
}
}
135. Candy
class Solution {
public int candy(int[] ratings) {
int[] count = new int[ratings.length];
count[0] = 1;
for(int i = 1; i < ratings.length; i++) {
if(ratings[i] > ratings[i - 1]) {
count[i] = count[i - 1] + 1;
} else {
count[i] = 1;
}
}
for(int i = ratings.length -2; i >= 0; i--) {
if(ratings[i] > ratings[i + 1]) {
count[i] = Math.max(count[i], count[i + 1] + 1);
}
}
int res = 0;
for(int c : count) {
res += c;
}
return res;
}
}
409. Longest Palindrome
class Solution {
public int longestPalindrome(String s) {
Set<Character> set = new HashSet();
int count = 0;
for(int i = 0; i < s.length(); i++) {
if(set.contains(s.charAt(i))) {
count += 2;
set.remove(s.charAt(i));
} else {
set.add(s.charAt(i));
}
}
if(set.size() > 0) {
count++;
}
return count;
}
}
228. Summary Ranges
class Solution {
public List<String> summaryRanges(int[] nums) {
ArrayList<String> all = new ArrayList();
for(int i = 0; i < nums.length; i++) {
int start = nums[i];
while((i + 1) < nums.length && nums[i] + 1 == nums[i + 1]) {
i++;
}
if(start != nums[i]) {
all.add("" + start + "->" + nums[i]);
} else{
all.add("" + start);
}
}
return all;
}
}
169. Majority Element
class Solution {
public int majorityElement(int[] nums) {
int n = nums.length;
Map<Integer, Integer> map = new HashMap();
for(int i = 0; i < n; i++) {
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
}
for(Map.Entry<Integer, Integer> entry: map.entrySet()){
if(entry.getValue() > n / 2) {
return entry.getKey();
}
}
return 0;
}
}