贪心day5continue
56. 合并区间
class Solution {
public int[][] merge(int[][] intervals) {
//按左边界排 相等则右边界
Arrays.sort(intervals, (o1, o2) -> {
if (o1[0] == o2[0]) return Integer.compare(o1[1], o2[1]);
return Integer.compare(o1[0], o2[0]);
});
List<int[]> res = new ArrayList<>();
int start = intervals[0][0], preEnd = intervals[0][1], i;
for (i = 1; i < intervals.length; i++) {
//找到不重叠的区间 把前面所有区间合并
if (intervals[i][0] > preEnd) {
res.add(new int[]{start, preEnd});
start = intervals[i][0];
}
preEnd = Math.max(preEnd, intervals[i][1]);
}
//遍历结束,最后一个区间未合并
res.add(new int[]{start, preEnd})
return res.toArray(new int[res.size()][]);
}
}
738. 单调递增的数字
class Solution {
public int monotoneIncreasingDigits(int n) {
String s = String.valueOf(n);
int len = s.length();
if (len == 1) {
return n;
}
//反向遍历
char[] array = s.toCharArray();
int start = len;
for (int i = len - 1; i > 0; i--) {
//后面数大于前面数位,前面数位-1 后面数位变9(未避免重复变9,可以将某数位以后需要变9的位置存起来,最后变一次9即可)
if (array[i] < array[i - 1]) {
array[i - 1] -= 1;
start = i;
}
}
for (int i = start; i < len; i++) {
array[i] = '9';
}
return Integer.parseInt(String.valueOf(array));
}
}
714. 买卖股票的最佳时机含手续费
class Solution {
public int maxProfit(int[] prices, int fee) {
if (prices.length == 1) {
return 0;
}
int buyIn = prices[0], res = 0;
for (int i = 1; i < prices.length; i++) {
//最低价买入
buyIn = Math.min(buyIn, prices[i]);
int profit = prices[i] - buyIn - fee;
//此时卖或买划不来 此步骤可以省略
// if (profit <= 0 || prices[i] > buyIn) {
// continue;
// }
if (profit > 0) {
//有利润我就计算一下利润 假设卖出
res += profit;
//如果这次用buyIn计算了利润 下一次再用此prices[i]计算利润的时候应该不计手续费;又或者下一天价格比此处不计手续费的prices[i]价格还低的话 上述在prices[i]卖出的假设就成立了。
buyIn = prices[i] - fee;
}
}
return res;
}
}
上述贪心思路可优化如下
//优化
class Solution {
public int maxProfit(int[] prices, int fee) {
int buyIn = prices[0] + fee, res = 0;
for (int p : prices) {
if (buyIn > p + fee) {
buyIn = p + fee;
} else if (p > buyIn){
res += p - buyIn;
buyIn = p;
}
}
return res;
}
}