5613. 最富有客户的资产总量
题目-5613. 最富有客户的资产总量
只会水水简单题了。扫描求和,选最大,ac,比赛结束。
class Solution {
public int maximumWealth(int[][] accounts) {
int[] sum = new int[accounts.length];
for (int i = 0; i < accounts.length; i++){
for (int j = 0 ; j < accounts[i].length; j++){
sum[i] += accounts[i][j];
}
}
int max = 0;
for (int i = 0; i< accounts.length; i++){
if (sum[i] > max){
max = sum[i];
}
}
return max;
}
}
5614. 找出最具竞争力的子序列
class Solution {
public int[] mostCompetitive(int[] nums, int k) {
int n = nums.length;
int[] res = new int[k];
Stack<Integer> st = new Stack<>();
int cnt = n - k;
for (int i = 0; i < n; i++){
while (! st.isEmpty() && cnt > 0 && nums[i] < nums[st.peek()]){
st.pop();
cnt--;
}
st.push(i);
}
for (int i = 0; i < cnt; i++){
st.pop();
}
int j = k - 1;
while (! st.isEmpty()){
res[j] = nums[st.pop()];
j--;
}
return res;
}
}
5615. 使数组互补的最少操作次数
题目-5615. 使数组互补的最少操作次数
题解见差分,日后想明白再补。
class Solution {
public int minMoves(int[] nums, int limit) {
int[] differ = new int[limit * 2 + 2];
int n = nums.length;
for (int i = 0; i < n / 2; i++){
int a = nums[i];
int b = nums[n - i - 1];
int max = a > b ? a : b;
int min = a < b ? a : b;
differ[1 + min] --;
differ[min + max] --;
differ[min + max + 1] ++;
differ[max + limit + 1] ++;
}
int res = n;
int now = n;
for (int i = 2; i <= 2 * limit; i++){
now += differ[i];
res = Math.min(res, now);
}
return res;
}
}
5616. 数组的最小偏移量
题目-5616. 数组的最小偏移量
对于奇数,只能操作一次,即乘2, 对于偶数,可以一直除2,直到变成奇数。
因此,先把奇数都乘2,变成偶数。
维护一个堆,最大差值则就是堆顶与堆底的差。计算堆顶与堆底的差值,若堆顶是偶数,则除2重新插入,一直到无法更新为止。
class Solution {
public int minimumDeviation(int[] nums) {
TreeSet<Integer> set = new TreeSet<>();
for (int num : nums){
set.add(num % 2 == 0 ? num : num * 2);
}
int res = set.last() - set.first();
while (res > 0 && set.last() % 2 == 0){
int max = set.last();
set.remove(max);
set.add(max / 2);
res = Math.min(res, set.last() - set.first());
}
return res;
}
}