zoukankan      html  css  js  c++  java
  • LeetCode | 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 the stock), design an algorithm to find the maximum profit.

    题目说只能完成一笔交易,即只能买、卖一次

     

    //maxprofit = max{A[j]-A[i] , j>i},即找数组两元素的最大的差值
    public class Solution {
        public int maxProfit(int[] prices) {
            if(prices.length <=1) return 0;
            
            int maxProfit = 0;
            for(int i=0; i<prices.length; i++){           //两重循环,提示超时。。。。。
                for(int j=i+1; j<prices.length; j++){
                    int profit = prices[j] - prices[i];
                    if(profit > maxProfit) maxProfit=profit;
                }
            }
            return maxProfit;
        }
    }

    题目给出的提示tags:array,dynamic programming,即提示用动态规划来写(动态规划参考研一上运筹学课件)

    1. 适合用动态规划来求解的仅是一类特殊的多阶段决策问题,即无后效性(马尔科夫性)的多阶段决策过程。

    2. 动态规划的最优性原理:作为整个过程的最优策略具有这样的性质,即无论过去的状态和决策如何,相对于前面决策所形成的状态而言,余下的决策序列必然构成最优子策略。

    <span style="font-size:10px;">//动态规划的思想,将此问题作为一个多阶段决策过程
    //在第i+1天要根据前i天决策所形成的状态【即前i天中的最低股票价格min_price和前i天所能获得的最大收益maxProfit】做出决策:
    //1. 在第i+1天卖掉股票,则收益是prices[i]-min_price
    //2. 在第i+1天不卖股票,则收益是前i天的maxProfit</span>
    <span style="font-size:10px;">public class Solution {
        public int maxProfit(int[] prices) {
            if(prices.length <=1) return 0;
            
            int maxProfit = 0;
            int min_price = prices[0];
            for(int i=0; i<prices.length; i++){
                if(prices[i]<min_price) min_price=prices[i];     //总是取已知的最低价格作为股票的买入点
                if(prices[i]-min_price > maxProfit) maxProfit=prices[i]-min_price;   //在第i+1天做出决策
            }
            return maxProfit;
        }
    }</span>



  • 相关阅读:
    关于Web登陆安全
    HttpWebRequest 忽略证书
    C# 语音识别(文字to语音、语音to文字)
    Microsoft Visual Studio 11(ISO、Web Installer)、.NET Framework 4.5 等下载地址
    ubuntu硬盘安装及启动,menu.lst
    下载虾米音乐的歌词
    sublime text在linux下一键编译c和c++程序的配置文件
    foobar2000专辑封面混乱解决方法
    qt creator纯C或C++项目在windows下的命令行中文乱码解决
    婚姻就是嫁给习惯和性格(转)
  • 原文地址:https://www.cnblogs.com/dosmile/p/6444461.html
Copyright © 2011-2022 走看看