D28|leetcode 122、55、45

122.?買賣股票的最佳時(shí)機(jī) II

思路:

本題就是求解利潤的最大值,所以如果相鄰兩天的利潤是正數(shù),則可以繼續(xù)持有,若是負(fù)數(shù)則就應(yīng)該舍棄,從下一個(gè)利潤為正數(shù)的前一天買入。

代碼:

class Solution {

public:

? ? int maxProfit(vector<int>& prices) {

? ? ? ? int res=0;

? ? ? ? for(int i=1;i<prices.size();i++)

? ? ? ? {

? ? ? ? ? ? res+=max(prices[i]-prices[i-1],0);

? ? ? ? }

? ? ? ? return res;

? ? }

};


55.?跳躍游戲

思路:

這道題可以將思路轉(zhuǎn)變成覆蓋范圍能不能到達(dá)數(shù)組的末尾。假設(shè)某一位數(shù)組的值為m,這表示最多可以跳躍m步,計(jì)算跳的m步下一次跳躍能達(dá)到的最大范圍,不斷更新。

代碼:

class Solution {

public:

? ? bool canJump(vector<int>& nums) {

? ? ? ? int count=0;

? ? ? ? if(nums.size()==1) return true;

? ? ? ? for(int i=0;i<=count;i++)

? ? ? ? {

? ? ? ? ? ? count=max(i+nums[i],count);

? ? ? ? ? ? if(count>=nums.size()-1)return true;

? ? ? ? }

? ? ? ? return false;

? ? }

};


45.?跳躍游戲 II

思路:

這道題可以用貪心算法解決,也就是在每次跳躍能覆蓋的范圍內(nèi)取下一次跳躍能到達(dá)到的最大值。

代碼:

class Solution {

public:

? ? int jump(vector<int>& nums) {

? ? if(nums.size()==1) return 0;

? ? int cur=0;

? ? int next=0;

? ? int count=0;

? ? for(int i=0;i<nums.size();i++)

? ? {

? ? ? ? next=max(i+nums[i],next);

? ? ? ? if(i==cur)

? ? ? ? {

? ? ? ? ? ? if(cur<nums.size()-1)

? ? ? ? ? ? {

? ? ? ? ? ? ? ? count++;

? ? ? ? ? ? ? ? cur=next;

? ? ? ? ? ? ? ? if(next>=nums.size()-1)break;

? ? ? ? ? ? }else break;

? ? ? ? }

? ? }

? ? return count;

? ? }

};

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容