[LeetCode]--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 th

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: 5

max. 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: 0

In this case, no transaction is done, i.e. max profit = 0.

思路首先:动态规划
遍历数组时记录当前价格以前的最小价格curMin,记录昨天能够获得的最大利润maxProfit。对于今天,为了能获得此刻的最大利润,显然只能卖,或者不做任何操作。如果不做任何操作,显然还是昨天maxProfit。如果卖掉今天天的股票,显然prices[i]-curMin。

public int maxProfit(int[] prices) {
        if (prices.length == 0)
            return 0;
        int minPro = prices[0];
        int maxGap = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] - minPro > maxGap)
                maxGap = prices[i] - minPro;
            if (prices[i] < minPro)
                minPro = prices[i];
        }
        return maxGap;
    }
目录
相关文章
|
算法
LeetCode 309. Best Time to B & S Stock with CD
给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。 设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票)
53 0
LeetCode 309. Best Time to B & S Stock with CD
|
算法
LeetCode 188. Best Time to Buy and Sell Stock IV
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。
59 0
LeetCode 188. Best Time to Buy and Sell Stock IV
|
算法
LeetCode 123. Best Time to Buy and Sell Stock III
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。 注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
70 0
LeetCode 123. Best Time to Buy and Sell Stock III
|
算法
LeetCode 121. Best Time to Buy and Sell Stock
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 如果您最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
48 0
LeetCode 121. Best Time to Buy and Sell Stock
Leetcode-Easy 121. Best Time to Buy and Sell Stock
Leetcode-Easy 121. Best Time to Buy and Sell Stock
103 0
Leetcode-Easy 121. Best Time to Buy and Sell Stock
|
算法
LeetCode 121 Best Time to Buy and Sell Stock(股票买入卖出的最佳时间)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50814399 翻译 话说你有一个数组,其中第i个元素表示在第i天的股票价格。
837 0
|
算法
LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50829772 翻译 话说你有一个数组,其中第i个元素表示第i天的股票价格。
843 0
|
22天前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
1月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记