博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Best Time to Buy and Sell Stock III
阅读量:6984 次
发布时间:2019-06-27

本文共 1656 字,大约阅读时间需要 5 分钟。

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.

Note:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Ref:http://fisherlei.blogspot.com/2013/01/leetcode-best-time-to-buy-and-sell_3958.html

http://www.cnblogs.com/jasonC/p/3417722.html

[Thoughts]

前后两遍遍历,算出当前位置之前和之后的最大利润。

One dimensional dynamic planning.

Given an i, split the whole array into two parts:
[0,i] and [i+1, n], it generates two max value based on i, Max(0,i) and Max(i+1,n)
So, we can define the transformation function as:
Maxprofix = max(Max(0,i) + Max(i+1, n))  0<=i<n
Pre-processing Max(0,i) might be easy, but I didn't figure an efficient way to generate Max(i+1,n) in one pass.

 

1 public class Solution { 2     public int maxProfit(int[] prices) { 3         if(prices == null || prices.length == 0){ 4             return 0; 5         } 6          7         int[] firstProfit = new int[prices.length]; 8         int min = prices[0]; 9         for(int i =1; i < prices.length; i++){10             min = Math.min(min, prices[i]);11             firstProfit[i] = Math.max(firstProfit[i-1], prices[i] - min);12         }13         14         int result = 0;15         int rightPeek = prices[prices.length-1];16         for(int i = prices.length-1; i >=0; i--){17             rightPeek = Math.max(rightPeek, prices[i]);18             result = Math.max(result, firstProfit[i] + rightPeek - prices[i]);19         }20         return result;21     }22 }

 

 

 

转载于:https://www.cnblogs.com/RazerLu/p/3552842.html

你可能感兴趣的文章
Linux 学习笔记 (一)在VMware 中安装 Ubtuntu 以及 VMware tools
查看>>
经典测试用例
查看>>
3月16日学习内容整理:metaclass
查看>>
Vue和其他框架的区别
查看>>
【iPhone5概念机最新效果图曝光】
查看>>
深入浅出:5G和HTTP
查看>>
ES6-let和const命令
查看>>
java反射,代码优化
查看>>
python中获取当前所有的logger
查看>>
关于BDD100k数据输入处理mask变为56*56
查看>>
Reveal使用心法
查看>>
Directx11教程(18) D3D11管线(7)
查看>>
JVM系列二:GC策略&内存申请、对象衰老
查看>>
正则的[]与()
查看>>
OCP换题库了,052新加的考题及答案整理-第16题
查看>>
OCP新题,2019题库出现大量新题,062-第22题
查看>>
MySQL查询in操作 查询结果按in集合顺序显示(转)
查看>>
JavaScript中map函数和filter的简单举例
查看>>
RocketMq消息队列使用
查看>>
Dynamics CRM 提示“操作无效”
查看>>