当前位置: 首页> 教育> 就业 > 每日5题Day25 - LeetCode 121 - 125

每日5题Day25 - LeetCode 121 - 125

时间:2025/7/27 23:29:04来源:https://blog.csdn.net/alimamaalala/article/details/139697826 浏览次数:0次

每一步向前都是向自己的梦想更近一步,坚持不懈,勇往直前!

第一题:121. 买卖股票的最佳时机 - 力扣(LeetCode)

class Solution {public int maxProfit(int[] prices) {if(prices.length == 1){return 0;}//dp[0]代表最小值,dp[1]代表最大利润int[] dp = new int[2];dp[0] = prices[0];dp[1] = 0;for(int i = 1; i < prices.length; i++){dp[0] = Math.min(dp[0], prices[i]);dp[1] = Math.max(dp[1], prices[i] - dp[0]);}return dp[1];}
}

第二题:122. 买卖股票的最佳时机 II - 力扣(LeetCode)

class Solution {public int maxProfit(int[] prices) {//注意这个同一天卖掉//该题相当于计算每天我们能获得的利润//涨的时候都算,跌的时候都不算int res = 0;for(int i = 1; i < prices.length; i++){if(prices[i] - prices[i - 1] > 0){res += prices[i] - prices[i - 1];}}return res;}
}

第三题:123. 买卖股票的最佳时机 III - 力扣(LeetCode)

class Solution {public int maxProfit(int[] prices) {if(prices.length == 1){return 0;}//因为是最多是两笔交易//当为奇数时为买入的最低价//当为偶数时为卖出的最高价int[] dp = new int[4];dp[0] = -prices[0];dp[1] = 0;dp[2] = -prices[0];dp[3] = 0;for(int i = 1; i < prices.length; i++){dp[0] = Math.max(dp[0], -prices[i]);dp[1] = Math.max(dp[1], prices[i] + dp[0]);dp[2] = Math.max(dp[2], dp[1] - prices[i]);dp[3] = Math.max(dp[3], prices[i] + dp[2]);}return dp[3];}
}

第四题:124. 二叉树中的最大路径和 - 力扣(LeetCode)

class Solution {private int ans = Integer.MIN_VALUE;public int maxPathSum(TreeNode root) {dfs(root);return ans;}private int dfs(TreeNode node) {if (node == null)return 0; // 没有节点,和为 0int lVal = dfs(node.left); // 左子树最大链和int rVal = dfs(node.right); // 右子树最大链和ans = Math.max(ans, lVal + rVal + node.val); // 两条链拼成路径return Math.max(Math.max(lVal, rVal) + node.val, 0); // 当前子树最大链和}
}

 第五题:. - 力扣(LeetCode)

class Solution {public boolean isPalindrome(String s) {StringBuilder sb = new StringBuilder();for (char ch : s.toCharArray()) {if (Character.isLetterOrDigit(ch)) {sb.append(Character.toLowerCase(ch));}}String str = sb.toString();int l = 0, r = str.length() - 1;while (l < r) {if (str.charAt(l) != str.charAt(r)) {return false;}l++;r--;}return true;}
}

关键字:每日5题Day25 - LeetCode 121 - 125

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: