摆动序列 LeetCode 376
题目链接:[LeetCode 376 - 中等]
思路
贪心中的序列问题,有贪心的解决方法和DP的解决方法。
贪心:
class Solution {
public int wiggleMaxLength(int[] nums) {
if(nums.length <= 1){
return nums.length;
}
int curDiff = 0;
int preDiff = 0;
int count = 1;
for(int i=1;i<nums.length;i++){
curDiff = nums[i] - nums[i-1];
if((curDiff>0&&preDiff<=0)||(curDiff<0&&preDiff>=0)){
count++;
preDiff = curDiff;
}
}
return count;
}
}
单调递增的数字 LeetCode 738
题目链接:[LeetCode 738 - 中等]
思路
判断数组后的元素是否比数组前的元素大,如果是的话,则将前一个数组减1,后面的所有数组元素都变为9
贪心:
class Solution {
public int monotoneIncreasingDigits(int n) {
String s = String.valueOf(n);
char[] chars = s.toCharArray();
int start = s.length();
for(int i=s.length()-2;i>=0;i--){
if(chars[i]>chars[i+1]){
chars[i]--;
start=i+1;
}
}
for(int i=start;i<s.length();i++){
chars[i]='9';
}
return Integer.parseInt(String.valueOf(chars));
}
}
买卖股票的最佳时机 II LeetCode 122
题目链接:[LeetCode 122 - 中等]
思路
通过判断数组中的后一个价值是否大于前一个价值,如果大于,则计算利润。
贪心:
class Solution {
public int maxProfit(int[] prices) {
int result = 0;
for(int i=0;i<prices.length-1;i++){
if(prices[i]<prices[i+1]){
result += prices[i+1] - prices[i];
}
}
return result;
}
}
买卖股票的最佳时机含手续费 LeetCode 714
题目链接:[LeetCode 714 - 中等]
思路
使用动态规划的方式。
DP:
class Solution {
public int maxProfit(int[] prices, int fee) {
int len = prices.length;
int[][] dp = new int[len][2];
dp[0][0] = -prices[0];
for(int i=1;i<len;i++){
dp[i][0]=Math.max(dp[i-1][0],dp[i-1][1]-prices[i]);
dp[i][1]=Math.max(dp[i-1][0]+prices[i]-fee,dp[i-1][1]);
}
return Math.max(dp[len-1][0],dp[len-1][1]);
}
}