[LeetCode]第二十二题 :最佳时机买卖股票

题目描述:

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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 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
Explanation: In this case, no transaction is done, i.e. max profit = 0.

题目解释:

给出一组代表着股票每天价格的数组。

你只允许买卖一只股票,设计算法找出挣钱最多的买卖方法。注意你只能在买了股票之后才能卖。

题目解法:

1.我的解法:我这边采用的是比较笨的方法,遍历每天股票,找出股票差最大的值。因为最后一天买卖股票没有意义,因此遍历只需要从开始到倒数第二个位置即可;设置一个值记录当前股票差最大的值,然后比对之后的所有天数,先判断卖的钱是否比买的钱多,再判断差值是不是比之前最大值大,如果大,则最大值变为现在的最大值,否则不变化;最后返回最大的差值。代码如下:

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length == 0) return 0;
        int max = 0;
        for(int i = 0 ; i < prices.length - 1; i++) {
            for(int j = i + 1;j < prices.length; j++) {
                if(prices[j] > prices[i] && (prices[j] - prices[i]) > max) {
                    max = prices[j] - prices[i];
                }
            }
        }
        return max;
    }
}

发布了61 篇原创文章 · 获赞 2 · 访问量 8740

猜你喜欢

转载自blog.csdn.net/woaily1346/article/details/80943192