zoukankan      html  css  js  c++  java
  • LeetCode & Q121-Best Time to Buy and Sell Stock-Easy

    Array DP

    Description:

    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.
    

    先说明题目意思,刚开始我看了很久也没搞明白,去Discuss上才看明白了。就是说,Input数组表示这段时间每天的货物价格,你以某个价格买入,之后再以那天的价格卖出,获取利益。例如:

    Input: [7,1,5,3,6,4]
    在价格为1时买入,价格为6时卖出,可获利润为5
    Input: [7,6,4,3,1]
    一直再降价,所以不买该货物,利润为0
    Input: [2,4,1]
    第一天买,第二天卖,可获利为2
    Input: [3,2,6,5,0,3]
    第二天买,第三天卖出,获利为4,比价格为0时买入,价格为3时卖出获利更多
    

    my Solution:

    public class Solution {
        public int maxProfit(int[] prices) {
            int n = prices.length;
            int profit = 0;
            if (n == 0) {
                return profit;
            }
            else {
                int min = prices[0];
                int max = prices[0];
                for (int i = 1; i < n; i++) {
                    if (min >= prices[i]) {
                        min = prices[i];
                        max = min;
                    }
                    if (max <= prices[i]) {
                        max = prices[i];
                    }
                    profit = Math.max(profit, max-min);
                }
                return profit;
            }
        }
    }
    

    我的方法非常常规,这题最好的方法就是用动态规划的思想来解。

    Best Solution:

    public class Solution {
        public int maxProfit(int[] prices) {
            int maxCur = 0;
            int maxSoFar = 0;
            for (int i = 1; i < prices.length; i++) {
                maxCur = Math.max(0, maxCur + prices[i] - prices[i-1]);
                maxSoFar = Math.max(maxCur, maxSoFar);
            }
            return maxSoFar;
        }
    }
    

    我对动态规划的理解还不够深刻,还需要多学习,多做这方面的题,加油!

  • 相关阅读:
    2019-1-7 水晶报表
    2018-12-25工作记录 空白行===水晶报表
    2018-7-26-随笔-泛型
    2018-7-20-随笔-转换
    2018-7-18-随笔-接口
    2018-7-17-随笔-params和ref、out用法、事件访问器
    VPS安装metasploit-framework
    Mimiktaz抓取本机密码
    msfvenom生成各类Payload命令
    docker容器开启ssh远程登录
  • 原文地址:https://www.cnblogs.com/duyue6002/p/7182100.html
Copyright © 2011-2022 走看看