zoukankan      html  css  js  c++  java
  • Best Time to Buy and Sell Stock III

    Best Time to Buy and Sell Stock III

    问题:

    Say you have an array for which the ith element is the price of a given stock on day i.

    Design an algorithm to find the maximum profit. You may complete at most two transactions.

    思路:

      动态规划

    我的代码:

    public class Solution {
        public int maxProfit(int[] prices) {
            if(prices == null || prices.length <= 1)    return 0;
            int size = prices.length;
            int[] left = new int[size];  
            int[] right = new int[size];
            int min = prices[0];
            int max = prices[size-1];
            int rst = 0;
            for(int i=1; i<size; i++)
            {
                min = Math.min(min,prices[i]);
                left[i] = Math.max(left[i-1],prices[i]-min);
            }
            for(int j=size-2; j>=0; j--)
            {
                max = Math.max(max,prices[j]);
                right[j] = Math.max(right[j+1],max-prices[j]);
            }
            for(int k=0; k<size; k++)
            {
                rst = Math.max(rst, left[k]+right[k]);
            }
            return rst;
        }
    }
    View Code

    学习之处:

    • 对于动态规划的问题,也越来越有感觉了,也知道怎么找动态规划方程了,无非是逆向思维而已,但是有两种动态规划的方式还不太熟悉,如本题的这种渐进的方式left[i-1]<=left[i]<=left[i+1]如此下去求解出最优解 另外一种方式是全局的最优解是遍历所有局部最优解的最优解。
    • 对于想不出来的问题,应该考虑如下几个方面,是不是有规律?是不是可以分解成几个小的问题,进而递归求解或者动态规划求解?可不可以使用分治算法降低时间复杂度
    • 改掉坏习惯,生活,思考等
  • 相关阅读:
    Seaslog高性能日志系统学习
    同步、异步与阻塞、非阻塞、协程
    SQL常用增删改查语句
    js里的document对象大全(DOM操作)
    php的cURL资源的初步使用
    hive学习笔记(初级)
    使用NSIS制作可执行程序的安装包
    C#设置一个控件可以鼠标拖动
    C#画图超出屏幕的部分无法显示的解决方法
    C#获取当前不同网卡对应的iP
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4461299.html
Copyright © 2011-2022 走看看