題目
題目難度:簡單
給定一個數組,它的第 i 個元素是一支給定股票第 i 天的價格。
如果你最多隻允許完成一筆交易(即買入和賣出一支股票一次),設計一個算法來計算你所能獲取的最大利潤。
注意:你不能在買入股票前賣出股票。
示例1
輸入: [7,1,5,3,6,4]
輸出: 5
解釋: 在第 2 天(股票價格 = 1)的時候買入,
在第 5 天(股票價格 = 6)的時候賣出,最大利潤 = 6-1 = 5 。
注意利潤不能是 7-1 = 6,
因爲賣出價格需要大於買入價格;
同時,你不能在買入前賣出股票。
示例2
輸入: [7,6,4,3,1]
輸出: 0
解釋: 在這種情況下, 沒有交易完成, 所以最大利潤爲 0。
解題
一.暴力枚舉
雙重循環
class Solution {
public int maxProfit(int[] prices) {
int maxpro = 0;
for(int i = 0 ; i < prices.length ; i++){
for(int j = i ; j < prices.length ; j++){
maxpro = Math.max(maxpro,prices[j]-prices[i]);
}
}
return maxpro;
}
}
- 時間複雜度:O(N^2),這裏 N是股價數組的長度;
- 空間複雜度:O(1)
二.暴力枚舉的優化
單層循環
class Solution {
public int maxProfit(int[] prices) {
if(prices.length <= 1){
return 0;
}
int maxpro = 0;
int minpro = prices[0];
for(int i = 0 ; i < prices.length ; i++){
minpro = Math.min(minpro,prices[i]);
maxpro = Math.max(maxpro,prices[i]-minpro);
}
return maxpro;
}
}
三.動態規劃
還沒明白這題的動態規劃如何求解T-T!!