首页 > 代码库 > 121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:

Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

 

Example 2:

Input: [7, 6, 4, 3, 1]Output: 0In this case, no transaction is done, i.e. max profit = 0.

Solution1:
思路:分析base case,small case,然后找出规律。存到i天之前最小的money,然后比较第i天的price是不是比最小的小,如果是,更新min。
存到i天之前最大的profit,计算第i天的profit,比较是不是最大。之前有一个顾虑,如果第i天的price更新了,但是又出现非常大的数怎么办,
其实这个不用顾虑,相应的profit肯定也会更大。

public class Solution {    public int maxProfit(int[] prices) {        int buy=Integer.MAX_VALUE;        int profit=Integer.MIN_VALUE;        for(int i=0;i<prices.length;i++)        {        buy=Math.min(buy,prices[i]);        profit=Math.max(prices[i]-buy,profit);        }        return (profit==Integer.MIN_VALUE)?0:profit;}}

 

121. Best Time to Buy and Sell Stock