目次
LeeCode 122. 株を売買するのに最適な時期 II
LeeCode 55. ジャンプ ゲーム
LeeCode 45. ジャンピング ゲーム II
LeeCode 122. 株を売買するのに最適な時期 II
122. 株を売買するのに最適な時期 II - LeetCode
アイデア: 全体の利益を毎日の利益に分割します。
ローカル最適: 毎日のプラスの利益を収集し、グローバル最適: 最大利益を見つけます。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int result = 0;
for (int i = 1; i < prices.size(); i++) {
result += max(prices[i] - prices[i - 1] , 0);
}
return result;
}
};
時間計算量: O(n) 空間計算量: O(1)
LeeCode 55. ジャンプ ゲーム
アイデア: トピックの要件を、ジャンプ範囲が最後まで到達するかどうかに変換します。
局所最適解:毎回最大数のジャンプステップ(最大カバレッジ)を実行し、全体最適解:最終的に全体の最大カバレッジを取得し、最後まで到達できるかどうかを確認します。
class Solution {
public:
bool canJump(vector<int>& nums) {
int cover = 0;
if (nums.size() == 1) return true;
for (int i = 0; i <= cover; i++) {
cover = max(i + nums[i], cover);
if (cover >= nums.size() - 1) return true;
}
return false;
}
};
LeeCode 45. ジャンピング ゲーム II
アイデア: カバレッジがエンドポイントをカバーするまで、最小限のステップ数で最大カバレッジを増やします。
class Solution {
public:
int jump(vector<int>& nums) {
if (nums.size() == 1) return 0;
int curDistance = 0;
int ans = 0;
int nextDistance = 0;
for (int i = 0; i < nums.size() - 1; i++) {
nextDistance = max(nums[i] + i, nextDistance);
if (i == curDistance) {
ans++;
curDistance = nextDistance;
}
}
return ans;
}
};