You are given an array
prices
whereprices[i]
is the price of a given stock on theith
day.You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return
0
.给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0
Example 1:
Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.Example 2:
Input: prices = [7,6,4,3,1] Output: 0 Explanation: In this case, no transactions are done and the max profit = 0.Constraints:
1 <= prices.length <= 105
0 <= prices[i] <= 104
对于这种求最值得问题可以使用动态规划,贪心算法等等方法来计算,不过,对于那方面我还没有系统得学习,就先不用那些方法了,现在先来看看暴力和双指针法。
关于暴力法提交得时候会超时,不过我们需要得是掌握这种思想,哪种思想呢?
我们来看看这一题,总的来说就是给你一个无序数组,让你依次遍历两个数,并求取最值,这个时候大家第一反应肯定就是遍历,因为关于数组这些简单题中的解题方法就是那几种,我目前遇到的有双指针法,遍历,暴力匹配,动态规划,还有哈希,递归等等。这一题困扰我们的应该就是如何去求那个最值,先看暴力法。
class Solution {
public int maxProfit(int[] prices) {
// //暴力匹配,不过这种方法超时了
// int max = 0;
// for(int i = 0;i < prices.length;i++){
// for(int j = i + 1;j < prices.length;j++){
// int nowPrice = prices[j] - prices[i];//得到一次循环的最大利润
// if(nowPrice > max){
// max = nowPrice;
// }
// }
// }
// return max;
}
}
大家应该都能看懂,给一个假定的初始最大值,然后每次遍历进行比较。
再看看双指针。
class Solution {
public int maxProfit(int[] prices) {
//我们再用双指针法来看看,这道题的主要思想我们之前也遇到果,就是一组数组之间的遍历,求取最值
int slow = 0;
int fast = 1;
int max = 0;
while(fast < prices.length){
if(prices[fast] < prices[slow]){
slow = fast;//也就是sslow++
} else {
max = Math.max(prices[fast] - prices[slow],max);
}
fast++;
}
return max;
}
}