123-Best Time to Buy and Sell Stock III
来源:互联网 发布:java axis2 调用wsdl 编辑:程序博客网 时间:2024/06/05 17:55
题目
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).
分析
动态规划法
整个的收益相当于[0,i]和[i,size-1]的加和
所以就要先正序求收益,再逆序求收益
最后一次遍历求和
实现
/*Author:FancyDate: 2017-03-27Algorithm: 123-Best Time to Buy and Sell Stock IIITime Complexity: 0(n)*/class Solution {public: int maxProfit(vector<int>& prices) { if (prices.size() == 0||prices.size()==1) return 0; vector<int> forProfit(prices.size(),0), backProfit(prices.size(),0); int minPrice = prices[0]; int maxPrice = prices[prices.size()-1]; int maxPro = 0; //[0,i] 交易的最大收益 for (int i = 1; i < prices.size(); i++) { minPrice = min(minPrice, prices[i]); forProfit[i] = max(forProfit[i-1], prices[i] - minPrice); } //[i,size-1]交易的最大收益 for (int j = prices.size() - 2; j >= 0; j--) { maxPrice = max(maxPrice, prices[j]); backProfit[j] = max(backProfit[j + 1], maxPrice- prices[j]); } //最大收益为max([0,i]+[i,size-1]) for (int i = 0; i < prices.size(); i++) maxPro = max(maxPro, forProfit[i] + backProfit[i ]); return maxPro; }};
阅读全文
0 0
- LeetCode 123: Best Time to Buy and Sell Stock III
- LeetCode: Best Time to Buy and Sell Stock III [123]
- LeetCode 123 Best Time to Buy and Sell Stock III
- [leetcode 123] Best Time to Buy and Sell Stock III
- leetcode || 123、Best Time to Buy and Sell Stock III
- leetcode-123 Best Time to Buy and Sell Stock III
- leetcode 123: Best Time to Buy and Sell Stock III
- 123 Best Time to Buy and Sell Stock III [Leetcode]
- Best Time to Buy and Sell Stock III - LeetCode 123
- LeetCode 123: Best Time to Buy and Sell Stock III
- 123Best Time to Buy and Sell Stock III
- LeetCode 123 Best Time to Buy and Sell Stock III
- LeetCode 123 -- Best Time to Buy and Sell Stock III
- Leetcode 123 Best Time to Buy and Sell Stock III
- LeetCode 123 Best Time to Buy and Sell Stock III
- Leetcode Best Time to Buy and Sell Stock III 123
- 123-Best Time to Buy and Sell Stock III
- [Leetcode 123] Best Time to Buy and Sell Stock III
- 120-Triangle
- 设计模式(18)-Iterator 迭代器
- 121-Best Time to Buy and Sell Stock
- 94. Binary Tree Inorder Traversal 中序遍历
- Java
- 123-Best Time to Buy and Sell Stock III
- Maven:Failed to create a Maven project ‘…pom.xml’ already exists in VFS 解决
- 131-Palindrome Partitioning
- swift-判断是否已获得相机、相册权限
- 132-Palindrome Partitioning II
- 模型汇总17 基于Depthwise Separable Convolutions的Seq2Seq模型_SliceNet原理解析
- Windows下Anaconda2(Python2)和Anaconda3(Python3)的共存,Beautiful Soup模块的安装
- 141-Linked List Cycle
- JavaMail第三方库-sendCloud