持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第5天,点击查看活动详情
写在前面
今天我们继续来解答一道难度定义为简单的LeetCode算法题:买卖股票的最佳时机。
题目解读
从题目的标题来看,很有吸引力的一道题。
从题目的具体描述中来看,我们需要判断出一个数组中间断性最大的数值结果。
其实这种类型的题目,一般都可以通过暴力循环的方式来得出每一个结果后,再逐一进行比较,最后得到正确结果。
但是在leetcode中好像不太行,因为报错了。
所以只能另外用一个方法,那就是从一开始就算,经历单次循环后,将最小值得出即可。
这里需要赋上一个初始值,这个初始值最大可以设置成10001,因为题目中给出的提示:数组元素的数值范围在1到10000之间。
代码实现
第一次使用的是暴力循环的方式,结果提交直接报了提交超出时间限制。
代码如下:
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.maxProfit(new int[]{7,1,5,3,6,4}));
}
public int maxProfit(int[] prices) {
int result = 0;
for (int i = 0; i < prices.length - 1; i++) {
for (int j = i + 1; j < prices.length; j++) {
int profit = prices[j] - prices[i];
if (profit > result) {
result = profit;
}
}
}
return result;
}
}
第一次执行结果:
再次提交了一版,让这个世界不再暴力。
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.maxProfit(new int[]{7,1,5,3,6,4}));
}
public int maxProfit(int[] prices) {
int min = 10001;
int max = 0;
for (int price : prices) {
if (price < min) {
min = price;
} else if (price - min > max) {
max = price - min;
}
}
return max;
}
}
第二次执行结果:
这次的运行结果就很不错了,速度还不错的。
总结
今天的这道题,主要是要多组排列组合才能得到正确的结果,理解了其中的规律就很轻松了。