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>



  • 相关阅读:
    []*T *[]T *[]*T 傻傻分不清楚
    Linux设备树
    gdb使用
    LockBit 2.0 勒索软件全球肆虐,我们该如何防范?
    记一次粗浅的钓鱼样本分析过程
    部分sql注入总结
    Linux系统取证简述
    对抗样本攻击及防御实战
    区块链是否真的安全?黑客盗取价值6亿美金数字货币
    某团购CMS的SQL注入漏洞代码审计
  • 原文地址:https://www.cnblogs.com/dosmile/p/6444461.html
Copyright © 2011-2022 走看看