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

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

转自https://oj.leetcode.com/problems/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.* * Note:* You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).*               **********************************************************************************/class Solution {public:    // Dynamic Programming    //    //     Considering prices[n], and we have a position "i", we could have    //       1) the maxProfit1 for prices[0..i]      //       2) the maxProfit2 for proices[i..n]    //    //    So,     //      for 1) we can go through the prices[n] forwardly.    //          forward[i] = max( forward[i-1], price[i] - lowestPrice[0..i] )     //      for 2) we can go through the prices[n] backwoardly.    //          backward[i] = max( backward[i+1], highestPrice[i..n] - price[i])     //    int maxProfit(vector
&prices) { if (prices.size()<=1) return 0; int n = prices.size(); vector
forward(n); forward[0] = 0; int lowestBuyInPrice = prices[0]; for(int i=1; i
backward(n); backward[n-1] = 0; int highestSellOutPrice = prices[n-1]; for(int i=n-2; i>=0; i--){ backward[i] = max(backward[i+1], highestSellOutPrice - prices[i]); highestSellOutPrice = max(highestSellOutPrice, prices[i]); } int max_profit = 0; for(int i=0; i

转载地址:http://tsdoi.baihongyu.com/

你可能感兴趣的文章
注解的使用
查看>>
【转】inet_addr、inet_aton、inet_pton异同小结
查看>>
linux中绑定80端口失败
查看>>
关于链接失败 对xxxx ‘__gxx_personality_v0’未定义的引用
查看>>
关于char*类型返回值和字符串常量
查看>>
epoll的一些关键点和总结(一)
查看>>
epoll的一些关键点和总结(二)
查看>>
关于epoll边缘触发模式(ET)下的EPOLLOUT触发
查看>>
socket TCP编程中connect的一些坑
查看>>
从C++单例模式到线程安全
查看>>
浅谈C文件编译过程
查看>>
FOJ 1001之位图数据结构对程序的优化
查看>>
盛名之下,其实难副?——再读CMU巨著CSAPP
查看>>
Python 解压稀疏矩阵
查看>>
Go 交换切片内两个索引对应的值
查看>>
Go string函数与strconv.Itoa函数的区别
查看>>
Go strings.Split函数
查看>>
Jinja2模板过滤器
查看>>
Go strings.HasPrefix函数
查看>>
Git删除文件
查看>>