力扣简121 买卖股票的最佳时机*
想不到的优化思路
最开始自己就暴力 结果运行超时了,然后看了题解的暴力也是超时。
题解二只需要单次循环,运行结果如下
package leetcode01; /*给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。 你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子卖出该股票。设计一个算法来计算你所能获取的最大利润。 返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。*/ public class Solution121 { //这种暴力计算超时了呜呜呜 然后看了一下官方题解一,也是超时了。 // public static int maxProfit(int[] prices) { // int len = prices.length; // int res = 0; // for(int i=0;i<len-1;i++) { // for(int j=i+1;j<len;j++) { // if(prices[j]-prices[i]>=0) { // int temp=prices[j]-prices[i]; // res=Math.max(temp, res); // } // } // } // return res; // } public static int maxProfit(int[] prices) { int profit=0; int preMin=Integer.MAX_VALUE; for(int i=0;i<prices.length;i++) { if(prices[i]<preMin) { preMin=prices[i]; } else if(profit<prices[i]-preMin) { profit=prices[i]-preMin; } } return profit; } public static void main(String[] args) { // TODO Auto-generated method stub int[] a= {7,1,5,3,6,4}; int[] b= {7,6,4,3,1}; System.out.print(maxProfit(a)); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理