11package com .leosanqing .leetcode .easy ;
22
33/**
4- *描述 : 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
5- * 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
6- * 注意你不能在买入股票前卖出股票。
7- *
8- *示例1: 输入: [7,1,5,3,6,4]
9- * 输出: 5
10- * 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
11- * 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
12- *
13- *示例2 输入: [7,6,4,3,1]
14- * 输出: 0
15- * 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
4+ * 描述 : 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
5+ * 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
6+ * 注意你不能在买入股票前卖出股票。
7+ * <p>
8+ * 示例1: 输入: [7,1,5,3,6,4]
9+ * 输出: 5
10+ * 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
11+ * 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
12+ * <p>
13+ * 示例2 输入: [7,6,4,3,1]
14+ * 输出: 0
15+ * 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
1616 */
1717
1818public class _121_BestTimeToBuyAndSellStock {
1919
2020 /**
21- *
2221 * 直接暴力求解,遍历两次数组,求出最优解
2322 */
2423
25- public static int violence (int [] prices ){
26- if (prices == null || prices .length ==0 ) {
24+ public static int violence (int [] prices ) {
25+ if (prices == null || prices .length == 0 ) {
2726 return 0 ;
2827 }
2928 int maxProfit = 0 ;
3029 for (int i = 0 ; i < prices .length ; i ++) {
31- for (int j = i + 1 ; j < prices .length ; j ++) {
32- if (prices [j ]- prices [i ] >maxProfit ){
33- maxProfit = prices [j ]- prices [i ];
30+ for (int j = i + 1 ; j < prices .length ; j ++) {
31+ if (prices [j ] - prices [i ] > maxProfit ) {
32+ maxProfit = prices [j ] - prices [i ];
3433 }
3534
3635 }
@@ -40,31 +39,29 @@ public static int violence(int[] prices){
4039
4140
4241 /**
43- * 动态规划:
44- * 1.定义一个从最开始到当前位置的最小值
45- * 2.计算今天减去最小值的值,也就是当天的利润
46- * 3.比较当天的利润和之前的最大利润
42+ * 动态规划:
43+ * 1.定义一个从最开始到当前位置的最小值
44+ * 2.计算今天减去最小值的值,也就是当天的利润
45+ * 3.比较当天的利润和之前的最大利润
4746 */
48- public static int dp (int [] prices ){
49- if (prices == null || prices .length == 0 )
47+ public static int dp (int [] prices ) {
48+ if (prices == null || prices .length == 0 )
5049 return 0 ;
5150
52- int mixProfit = Integer .MAX_VALUE ;
51+ int minProfit = Integer .MAX_VALUE ;
5352 int maxProfit = 0 ;
5453
55- for (int i = 0 ; i < prices . length ; i ++ ) {
54+ for (int price : prices ) {
5655 //找到最小值
57- mixProfit = Math .min (mixProfit , prices [ i ] );
56+ minProfit = Math .min (minProfit , price );
5857 //比较当天的利润和最大利润
59- maxProfit = Math .max (maxProfit ,(prices [i ]-mixProfit ));
60-
58+ maxProfit = Math .max (maxProfit , (price - minProfit ));
6159 }
6260 return maxProfit ;
63-
6461 }
6562
6663 public static void main (String [] args ) {
67- int a [] = {7 ,6 , 4 , 3 , 1 };
64+ int [] a = {7 , 6 , 4 , 3 , 1 };
6865 System .out .println (violence (a ) == dp (a ));
6966 }
7067}
0 commit comments