1. 程式人生 > 其它 >LeetCode0121-買賣股票的最佳時機

LeetCode0121-買賣股票的最佳時機

技術標籤:LeetCodeleetcode演算法動態規劃買賣股票的最佳時機

LeetCode0121-買賣股票的最佳時機

題目:

給定一個數組,它的第 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。

程式碼:

/**
 * 0121-買賣股票的最佳時機
 * 給定一個數組,它的第 i 個元素是一支給定股票第 i 天的價格。
 * <p>
 * 如果你最多隻允許完成一筆交易(即買入和賣出一支股票一次),設計一個演算法來計算你所能獲取的最大利潤。
 * <p>
 * 注意:你不能在買入股票前賣出股票。
 * <p>
 * 示例 1:
 * <p>
 * 輸入: [7,1,5,3,6,4]
 * 輸出: 5
 * 解釋: 在第 2 天(股票價格 = 1)的時候買入,在第 5 天(股票價格 = 6)的時候賣出,最大利潤 = 6-1 = 5 。
 * 注意利潤不能是 7-1 = 6, 因為賣出價格需要大於買入價格;同時,你不能在買入前賣出股票。
 * <p>
 * 示例 2:
 * <p>
 * 輸入: [7,6,4,3,1]
 * 輸出: 0
 * 解釋: 在這種情況下, 沒有交易完成, 所以最大利潤為 0。
 */
/** * 暴力法 */ class Solution01 { public int maxProfit(int prices[]) { int length = prices.length; // 儲存最大收益 int profit = 0; for (int i = 0; i < length; i++) { for (int j = i + 1; j < length; j++) { int cur = prices[j] - prices[i]; if
(cur > profit) { profit = cur; } } } return profit; } } /** * 動態規劃 * 首先遍歷價格陣列,將每一天的價格減去前一天的價格,構建一個利潤陣列 profit[] 記錄每一天的利潤遍歷陣列 * 利用動態規劃的思想,求利潤陣列的最大子陣列的和,即為最大利潤 */ class Solution02 { public int maxProfit(int[] prices) { if (prices.length == 0) { return 0; } int[] profit = new int[prices.length]; profit[0] = 0; for (int i = 1; i < profit.length; i++) { profit[i] = prices[i] - prices[i - 1]; } int pre = profit[0]; int max = profit[0]; for (int i = 1; i < profit.length; i++) { pre = Math.max(profit[i], pre + profit[i]); max = Math.max(max, pre); } return max > 0 ? max : 0; } } /** * 測試 */ public class Study0121 { public static void main(String[] args) { System.out.println(new Solution02().maxProfit(new int[]{7, 1, 5, 3, 6, 4})); } }

結果:

在這裡插入圖片描述