122. 买卖股票的最佳时机 II
贪心
class Solution {
public int maxProfit(int[] prices) {
//贪心
int result = 0;
for(int i=1;i<prices.length;i++){
result+=Math.max(prices[i]-prices[i-1],0);
}
return result;
}
}
动态规划
class Solution {
public int maxProfit(int[] prices) {
int [][] dp = new int [prices.length][2];
dp[0][0]=0;
dp[0][1] = -prices[0];
for(int i=1;i<prices.length;i++){
dp[i][0] = Math.max(dp[i-1][1]+prices[i],dp[i-1][0]);
dp[i][1] = Math.max(dp[i-1][0] -prices[i],dp[i-1][1]);
}
return dp[prices.length-1][0];
}
}
55. 跳跃游戏
这题需要注意的是i的取值范围是coverRange
class Solution {
public boolean canJump(int[] nums) {
int n = nums.length;
if(n==1){
return true;
}
int coverRange = 0;
for(int i =0;i<=coverRange;i++){
coverRange = Math.max(coverRange,i+nums[i]);
if(coverRange>=n-1){
return true;
}
}
return false;
}
}
45.跳跃游戏 II
利用count来记录当前跳跃次数,maxDis为最大可以覆盖的区域,curDIs为目前最大可以覆盖的区域。当i到达当前可以覆盖的最大区域时,更新当前可达最大区域至最大可达区域,然后增加count。
class Solution {
public int jump(int[] nums) {
if (nums == null || nums.length == 0 || nums.length == 1) {
return 0;
}
int count =0 ;
int maxDis =0;
int curDis =0;
for(int i=0;i<nums.length;i++){
maxDis = Math.max(maxDis,i+nums[i]);
if(maxDis>=nums.length-1){
count++;
break;
}
if (i==curDis){
curDis = maxDis;
count++;
}
}
return count;
}
}