文章目錄
- 買賣股票的最佳時機
- 題目描述
- code
買賣股票的最佳時機
題目描述
給定一個數組,它的第 i 個元素是一支給定股票第 i 天的價格。
如果你最多隻允許完成一筆交易(即買入和賣出一支股票),設計一個算法來計算你所能擷取的最大利潤。
注意你不能在買入股票前賣出股票。
輸入: [7,1,5,3,6,4]
輸出: 5
解釋: 在第 2 天(股票價格 = 1)的時候買入,在第 5 天(股票價格 = 6)的時候賣出,最大利潤 = 6-1 = 5 。
注意利潤不能是 7-1 = 6, 因為賣出價格需要大于買入價格。
輸入: [7,6,4,3,1]
輸出: 0
解釋: 在這種情況下, 沒有交易完成, 是以最大利潤為 0。
code
import org.junit.Test;
public class Leetcode121 {
@Test
public void test() {
int[] prices = new int[]{7, 1, 5, 3, 6, 4};
Solution solution = new Solution();
System.out.println(solution.maxProfit(prices));
}
//買股票的最佳時機
//動态規劃轉台方程=> res= max(res, prices[i]-min_val);
//數組是每天股票的價格,要擷取最大的利益
class Solution {
public int maxProfit(int[] prices) {
int res = 0;
int min_val = Integer.MAX_VALUE;//integer目前最大值
for (int i = 0; i < prices.length; i++) {
min_val = Math.min(min_val, prices[i]);
//目前索引值和 min_val 進行比較,擷取最小值,然後res,和prices[i]
//收益最大= 最大的res, 和每天價格-目前最小值,進行比較,擷取最大值,這樣就擷取利潤最大值
//最大利益:是以是Max, 每天價格最大值和最小值的內插補點,就是利益
res = Math.max(res, prices[i] - min_val);
}
return res;
}
}
}