zoukankan      html  css  js  c++  java
  • 【LeetCode】121. 买卖股票的最佳时机

    题目链接:

    121. 买卖股票的最佳时机

    题目描述:

    给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

    如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。

    注意你不能在买入股票前卖出股票。

    示例:

    示例 1:

    输入:[7,1,5,3,6,4]
    输出:5
    解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
    

    示例 2:

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

    思路:

    买入和卖出构成一个数对,利润就是这个数对的差,最大利润就是所有数对差的最大值。(注意:卖出要在买入之后)

    思路一:

    本题最容易想到的方法应该是暴力法:找出数组中所有的数对并求出差,取其中的最大值即可,简单粗暴。时间复杂度:(O(n^2))

    思路二:

    在遍历数组时,我们可以顺便记录下其中的最小值(即股票最低价),作为买入的时间。同时,计算如果现在卖出,利润是多少,遍历完数组,即可求得最大利润。时间复杂度:(O(n))

    代码实现:

    思路一:

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

    思路二:

    class Solution {
        public int maxProfit(int[] prices) {
            if (prices.length < 2) {
                return 0;
            }
            // 初始化最大利润为0,股票最低价为第一天
            int maxProfit = 0, min = prices[0];
    
            for (int i = 1; i < prices.length; i++) {
                // 更新股票最低价
                if (prices[i] < min) {
                    min = prices[i];
                }
                // 更新最大利润
                if (prices[i] - min > maxProfit) {
                    maxProfit = prices[i] - min;
                }
            }
            return maxProfit;
        }
    }
    
  • 相关阅读:
    适配器模式
    注册模式
    工厂模式
    策略模式和注入控制反转
    验签
    php中加密和解密
    asp.net textbox keyup事件触发后台的textchange事件
    jquery $.post 返回json数据
    网页播放音频、视频文件——基于web的html 5的音乐播放器(转载)
    c# 柱状图(转载)
  • 原文地址:https://www.cnblogs.com/ME-WE/p/12448034.html
Copyright © 2011-2022 走看看