今日任务
122.买卖股票的最佳时机II
- 题目链接: https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/description/
- 题目描述:
Code
class Solution {
public:
int maxProfit(vector<int>& prices) {
// int profit = 0;
// strong_ordering cmp_less = strong_ordering::less;
// strong_ordering cmp_greater = strong_ordering::greater;
// int buy = 0;
// bool is_buy = false;
// for(int i = 1; i < prices.size(); i++){
// if(!is_buy && prices[i - 1] <=> prices[i] == cmp_less){
// buy = prices[i - 1];
// is_buy = true;
// }else if(is_buy && prices[i - 1] <=> prices[i] == cmp_greater){
// profit += prices[i - 1] - buy;
// is_buy = false;
// }
// }
// if(is_buy && prices.back() > buy){
// profit += prices.back() - buy;
// }
// return profit;
int ans = 0;
int pre = 0;
int n = prices.size();
bool flag = false;
for(int i = 1; i < n; i++){
int a = prices[i - 1], b = prices[i];
if(!flag && a < b){
pre = a;
flag = !flag;
}else if(flag && a > b){
ans += a - pre;
flag = !flag;
}
}
if(flag && prices.back() > pre){
ans += prices.back() - pre;
}
return ans;
}
};
55. 跳跃游戏
- 题目链接: https://leetcode.cn/problems/jump-game/description/
- 题目描述:
Code
class Solution {
public:
bool canJump(vector<int>& nums) {
// int target = 1;
// for(auto it = nums.rbegin() + 1; it != nums.rend(); it++){
// if(*it >= target){
// target = 1;
// }else{
// target++;
// }
// }
// return target == 1;
// int mx_idx = 0;
// for(int i = 0; i < nums.size(); i++){
// if(i > mx_idx){
// return false;
// }else{
// mx_idx = max(mx_idx, i + nums[i]);
// }
// }
// return true;
int mx_idx = 0;
for(int i = 0; mx_idx < nums.size() - 1; i++){
if(i > mx_idx){
return false;
}else{
mx_idx = max(mx_idx, i + nums[i]);
}
}
return true;
}
};
45.跳跃游戏II
- 题目链接: https://leetcode.cn/problems/jump-game-ii/description/
- 题目描述:
Code
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
int mx_index = nums[0];
int ans = 0;
for(int i = 1; i < n; ){
int mx = 0;
while(i < n && i <= mx_index){
mx = max(mx, i + nums[i]);
i++;
}
mx_index = mx;
ans++;
}
return ans;
}
};
1005. K 次取反后最大化的数组和
- 题目链接: https://leetcode.cn/problems/maximize-sum-of-array-after-k-negations/
- 题目描述:
Code
class Solution {
public:
int largestSumAfterKNegations(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int>> que(nums.begin(), nums.end());
int sum = reduce(nums.begin(), nums.end(), 0);
while(k--){
int t = que.top();
que.pop();
if(t < 0){
que.push(-t);
sum += -2 * t;
}
else if(t > 0){
sum += (k + 1) % 2 == 0 ? 0 : -t * 2;
break;
}
else {
break;
}
}
return sum;
}
};