• 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>



  • 相关阅读:
    Nim or not Nim? hdu3032 SG值打表找规律
    Maximum 贪心
    The Super Powers
    LCM Cardinality 暴力
    Longge's problem poj2480 欧拉函数,gcd
    GCD hdu2588
    Perfect Pth Powers poj1730
    6656 Watching the Kangaroo
    yield 小用
    wpf DropDownButton 源码
  • 原文地址:https://www.cnblogs.com/dosmile/p/6444461.html
Copyright © 2020-2023  润新知