題目描述
給定一個數組,它的第 i 個元素是一支給定股票第 i 天的價格。
如果你最多隻允許完成一筆交易(即買入和賣出一支股票一次),設計一個算法來計算你所能獲取的最大利潤。
!!! 不能在買入股票前賣出股票 !!!
解題思路
思路1:一次遍歷 O(N)
-
1.維護兩個整數,maxnum和minnum,用來記錄區間最大值和最小值;
-
2.遍歷數組:
- 當元素item 大於 maxnum 時,最大值mannum更新爲item,此時比較最大值和最小值的差值 sub 與當前記錄的臨時最大利潤profit的大小關係,如果sub > profit,就更新profit,小於則不更新;
- 當元素item 小於 minnum 時,最小值minnum和最大值maxnum都更新爲item;
-
3.遍歷結束後直接返回profit。
思路2:兩層遍歷,暴力求解 O(N²)
兩層遍歷的過程中不斷比較兩數之差與profit的大小關係,更新找到最大利潤,思路比較通俗易懂,但是時間複雜度高。
代碼實現(Java)
/**
* @author : flower48237
* @2020/3/23 16:46
* @title : LeetCode精選TOP面試題121.買賣股票的最佳時機
*/
public class Solution {
public int maxProfit(int[] prices) {
if (prices.length == 0 || prices.length == 1){
return 0;
}
// 法 1 ,一次遍歷
int maxnum = prices[0], minnum = prices[0];
int profit= 0;
for (int i = 1; i < prices.length; i++){
if (prices[i] > maxnum){
maxnum = prices[i];
if (maxnum - minnum > profit){
profit= maxnum - minnum;
}
}
if (prices[i] < minnum){
minnum = prices[i];
maxnum = prices[i];
}
}
return profit;
/* 法 2 暴力求解
int maxprofit = 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 > maxprofit)
maxprofit = profit;
}
}
return maxprofit;
*/
}
}
做完題之後膜拜大佬的解題思路,果然我是白癡級別,大佬的解題思路實在是太強了。
labuladong大佬的文章:一個方法團滅 6 道股票問題
ivan_allen大佬的文章:dp 7 行簡約風格