【LeetCode】121.best-time-to-buy-and-sell-stock

来源:互联网 发布:淘宝自动回复短语 创意 编辑:程序博客网 时间:2024/06/01 08:54

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.


方法一:O(n^2)

1、遍历所有i,对每个i遍历j from i+1 to n,找到最大的差。但没有体现动态规划的思想。

2、遍历所有i,对每个i找前i-1个中最小的元素,若arr[i]-min>profit[i-1],则更新profit[i],否则,profit[i]=profit[i-1]。体现了动态规划思想,但复杂度还是很高。


方法二:O(n)

仔细分析问题可以发现,核心就是找波谷min,然后计算其之后的最大差(找波峰max)。


public class Solution {    public int maxProfit(int prices[]) {        int minprice = Integer.MAX_VALUE;        int maxprofit = 0;        for (int i = 0; i < prices.length; i++) {            if (prices[i] < minprice)                minprice = prices[i];            else if (prices[i] - minprice > maxprofit)                maxprofit = prices[i] - minprice;        }        return maxprofit;    }}


阅读全文
0 0
原创粉丝点击