LeetCode 1646 获取生成数组中的最大值[数组] HERODING的LeetCode之路
Posted HERODING23
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 1646 获取生成数组中的最大值[数组] HERODING的LeetCode之路相关的知识,希望对你有一定的参考价值。
解题思路:
直接依照题意,把所有的数表示出来,算取最大值即可,代码如下:
class Solution {
public:
int getMaximumGenerated(int n) {
if(n == 0) {
return 0;
}
vector<int> nums(n + 1);
nums[1] = 1;
for(int i = 2; i <= n; i ++) {
if(i % 2 == 0) {
nums[i] = nums[i / 2];
} else {
nums[i] = nums[i / 2] + nums[i / 2 + 1];
}
}
return *max_element(nums.begin(), nums.end());
}
};
判断过程可以化简,无需判断,直接通过i % 2,将两种情况合并成一个情况实现(因为一种是另一种的子动作),代码如下:
class Solution {
public:
int getMaximumGenerated(int n) {
if(n == 0) {
return 0;
}
vector<int> nums(n + 1);
nums[1] = 1;
for(int i = 2; i <= n; i ++) {
nums[i] = nums[i / 2] + i % 2 * nums[i / 2 + 1];
}
return *max_element(nums.begin(), nums.end());
}
};
以上是关于LeetCode 1646 获取生成数组中的最大值[数组] HERODING的LeetCode之路的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 789. 逃脱阻碍者(贪心) / 1646. 获取生成数组中的最大值 / 787. K 站中转内最便宜的航班(有限制的最短路,重新审视迪杰斯特拉,动态规划)