My LeetCode Diary - Day32 Greedy Algo
122. Best Time to Buy and Sell Stock II
Link
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int[][] dp = new int[n][2];
for (int i = 0; i < n;i++) {
if (i == 0) {
dp[i][0] = 0;
dp[i][1] = -prices[i];
continue;
}
dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i]);
dp[i][1] = Math.max(dp[i-1][1],dp[i-1][0] - prices[i]);
}
return dp[n-1][0];
}
}
55. Jump Game
Link
class Solution {
public boolean canJump(int[] nums) {
if (nums.length == 1) {
return true;
}
int coverRange = 0;
for (int i = 0; i <= coverRange; i++) {
coverRange = Math.max(coverRange, i + nums[i]);
if (coverRange >= nums.length - 1) {
return true;
}
}
return false;
}
}
45. Jump Game II
Link
class Solution {
public int jump(int[] nums) {
int result = 0;
int end = 0;
int temp = 0;
for (int i = 0; i <= end && end < nums.length - 1; ++i) {
temp = Math.max(temp, i + nums[i]);
if (i == end) {
end = temp;
result++;
}
}
return result;
}
}