<LeetCode>121. 买卖股票的最佳时机

题目:

假设你有一个数组,其中第 i 个元素是一支给定股票第 i 天的价格。

如果您只能完成最多一笔交易(即买入和卖出一股股票),则设计一个算法来找到最大的利润。

示例1:

1 输入: [7, 1, 5, 3, 6, 4]
2 输出: 5
3 
4 最大利润 = 6-1 = 5(不是 7-1 = 6, 因为卖出价格需要大于买入价格)

示例2:

1 输入: [7, 6, 4, 3, 1]
2 输出: 0
3 
4 在这种情况下, 没有交易完成, 即最大利润为 0。

思路:

result 永远保存最大的差值,buy 永远保存最小的价格。

code:

 1 public class Main{
 2     public static void main(String[] args) {
 3         int[] prices ={7, 1, 5, 3, 6, 4};
 4         System.out.println(maxProfit(prices));
 5 
 6     }
 7     public static int maxProfit(int[] prices){
 8         int buy = Integer.MAX_VALUE;
 9         int result = 0;
10         for (int i = 1; i<prices.length;i++){
11             buy = Math.min(prices[i], buy);
12             result = Math.max(result, prices[i] - buy);
13         }
14         return result;
15     }
16 
17 }

 

posted @ 2018-09-03 19:19  110255  阅读(109)  评论(0编辑  收藏  举报