
解题思路:
- 初始化变量:
- minPrice:记录最低买入价。
- maxProfit:记录当前最大利润。
- 遍历数组:
- 若当前价格低于已记录的最低价,则更新最低价。
- 否则计算当前价格与最低价的差值,并尝试更新最大利润。
Java代码:
class Solution {public int maxProfit(int[] prices) {int minPrice = prices[0];int maxProfit = 0;for (int i = 1; i < prices.length; i++) {if (prices[i] < minPrice) {minPrice = prices[i];} else {maxProfit = Math.max(maxProfit, prices[i] - minPrice);}}return maxProfit;}
}
复杂度分析:

解题思路:
- 初始化变量:
- 遍历数组:
- 如果当前的遍历位置 i > 当前的最远距离,break。
- 更新总的最远距离,如果总的最远距离超过数组长度,返回 true。
- 如果循环结束,说明无法到达最后一个下标,返回 false。
Java代码:
class Solution {public boolean canJump(int[] nums) {int maxReach = 0;for (int i = 0; i < nums.length; i++) {if (i > maxReach) break;maxReach = Math.max(maxReach, i + nums[i]);if (maxReach >= nums.length - 1) return true;}return false;}
}
复杂度分析: