贪心与动态规划核心题型实战解析
一、跳跃游戏 II:最小跳跃步数计算
给定一个非负整数序列,每个数值代表从该位置可向前跃迁的最大跨度。核心目标是计算抵达序列末端所需的最少跃迁次数。采用边界扩展策略:遍历过程中动态维护当前跃迁次数所能覆盖的最远索引。当遍历指针触及当前边界时,说明必须执行一次新的跃迁,此时将边界更新为已扫描范围内能到达的最远位置,并累加计数。该方法避免了对原数组的修改,空间复杂度降至常数级。
public int calculateMinJumps(int[] steps) {
if (steps == null || steps.length < 2) return 0;
int jumpCount = 0;
int currentBoundary = 0;
int farthestReach = 0;
for (int idx = 0; idx < steps.length - 1; idx++) {
farthestReach = Math.max(farthestReach, idx + steps[idx]);
if (idx == currentBoundary) {
jumpCount++;
currentBoundary = farthestReach;
if (currentBoundary >= steps.length - 1) break;
}
}
return jumpCount;
}二、跳跃游戏:路径连通性判定
判断是否存在从起点到终点的合法跃迁路径。算法通过维护一个全局最大可达索引来模拟前进过程。若当前扫描位置超出了已知最大可达范围,则路径中断,直接返回失败;否则持续根据当前位置的跨度更新最大可达索引。一旦该索引覆盖终点,即可提前判定为可达。
public boolean checkPathReachable(int[] jumpLengths) {
if (jumpLengths == null) return false;
int maxReachablePos = 0;
for (int pos = 0; pos < jumpLengths.length; pos++) {
if (pos > maxReachablePos) return false;
maxReachablePos = Math.max(maxReachablePos, pos + jumpLengths[pos]);
if (maxReachablePos >= jumpLengths.length - 1) return true;
}
return true;
}三、买卖股票的最佳时机 II:无限次交易利润最大化
在允许任意次交易且持仓互斥的前提下,求取总收益峰值。由于交易次数无限制,任何相邻交易日之间的价格上涨均可转化为实际利润。无需寻找全局波谷与波峰,只需遍历价格序列,将每一段正向价差累加即可等价于最优买卖策略。
public int computeTotalProfit(int[] marketPrices) {
int accumulatedGain = 0;
for (int day = 1; day < marketPrices.length; day++) {
int dailyDiff = marketPrices[day] - marketPrices[day - 1];
if (dailyDiff > 0) {
accumulatedGain += dailyDiff;
}
}
return accumulatedGain;
}四、最大子数组和:连续区间极值求解
寻找整数序列中元素和最大的连续子区间。采用状态压缩的动态规划思想(Kadane算法):定义局部状态为以当前元素结尾的最大连续和。若前置子区间和为负值,则将其舍弃并从当前元素重新开始累积;同时使用全局变量持续追踪历史最大值,确保最终结果为全局最优。
public int findOptimalSubarraySum(int[] data) {
if (data.length == 0) return 0;
int localMax = data[0];
int globalMax = data[0];
for (int idx = 1; idx < data.length; idx++) {
localMax = Math.max(data[idx], localMax + data[idx]);
globalMax = Math.max(globalMax, localMax);
}
return globalMax;
}五、摆动序列:最长交替差值子序列
摆动序列要求相邻元素差值的正负符号严格交替。通过线性扫描计算相邻差值,并记录上一次有效差值的变化方向。仅当首次出现非零差值,或当前差值方向与历史方向相反时,才将当前元素纳入摆动序列并更新方向记录。该策略可有效跳过平台期(相等元素)并精准统计峰值数量。
public int getLongestWiggleLen(int[] sequence) {
if (sequence.length < 2) return sequence.length;
int wiggleCount = 1;
Integer lastTrend = null;
for (int i = 1; i < sequence.length; i++) {
int diff = sequence[i] - sequence[i - 1];
if (diff == 0) continue;
int currentTrend = diff > 0 ? 1 : -1;
if (lastTrend == null || currentTrend != lastTrend) {
wiggleCount++;
lastTrend = currentTrend;
}
}
return wiggleCount;
}六、分发饼干:资源匹配最优化
给定儿童胃口阈值与饼干容量数组,求最多可满足的儿童数量。采用升序排序结合双指针扫描的贪心策略:优先尝试用最小容量的饼干去匹配胃口最小的儿童。若当前饼干满足阈值,则双方指针同步后移并计数;若不满足,则仅饼干指针后移以尝试更大容量。该分配逻辑确保了容量资源的利用率最大化。
import java.util.Arrays;
public int maximizeSatisfiedChildren(int[] appetiteLevels, int[] cookieCapacities) {
Arrays.sort(appetiteLevels);
Arrays.sort(cookieCapacities);
int childPtr = 0;
int cookiePtr = 0;
int matchCount = 0;
while (childPtr < appetiteLevels.length && cookiePtr < cookieCapacities.length) {
if (cookieCapacities[cookiePtr] >= appetiteLevels[childPtr]) {
matchCount++;
childPtr++;
}
cookiePtr++;
}
return matchCount;
}