week14-leetcode #121-BestTimetoBuyandSellStock
来源:互联网 发布:windows ndk环境搭建 编辑:程序博客网 时间:2024/06/07 06:19
week14-leetcode #121-BestTimetoBuyandSellStock
链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
Question
Say you have an array for which the
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.
Example
Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)Input: [7, 6, 4, 3, 1]Output: 0In this case, no transaction is done, i.e. max profit = 0.
Solution1 — 非DP
class Solution {public: int maxProfit(vector<int>& prices) { int min_val = 999999; int max_diff = 0; for (int i = 0; i < prices.size(); i++) { min_val = (min_val > prices[i]) ? prices[i]: min_val; max_diff = (max_diff < prices[i]-min_val) ? (prices[i]-min_val) : max_diff; } return max_diff; }};
思路:遍历一次prices数组,到位置
Solution2 — DP
class Solution {public: int maxProfit(vector<int>& prices) { int size = prices.size(); int *max_profit = new int[size]; int *min_val = new int[size]; min_val[0] = prices[0]; max_profit[0] = 0; for (int i = 1; i < size; i++) { min_val[i] = min(min_val[i-1], prices[i]); max_profit[i] = max(max_profit[i-1], prices[i]-min_val[i]); } return max_profit[size-1]; }};
思路:
初始化
阅读全文
0 0
- week14-leetcode #121-BestTimetoBuyandSellStock
- leetcode week14
- Leetcode Week14
- 121BestTimetoBuyandSellStock.java
- week15-leetcode #122-BestTimetoBuyandSellStock II
- week15-leetcode #122-BestTimetoBuyandSellStock II
- LeetCode题解 week14
- LeetCode Week14: Longest Valid Parentheses
- LeetCode#648 Replace Words (week14)
- LeetCode#554 Brick Wall (week14)
- LeetCode#494 Target Sum (week14)
- Leetcode: 216. Combination Sum III(Week14, Medium)
- 算法设计Week14 LeetCode Algorithms Problem #91 Decode Ways
- Leetcode 416 Partition Equal Subset Sum (算法分析week14)
- [LeetCode-Algorithms-75] "Sort Colors" (2017.12.7-WEEK14)
- [LeetCode-Algorithms-537] "Complex Number Multiplication" (2017.12.7-WEEK14)
- Leetcode 646. Maximum Length of Pair Chain(算法分析week14)
- Week14 总结
- matplotlib
- 前端工程师
- 队列
- Bootstrap UI 编辑器
- 445. Add Two Numbers II
- week14-leetcode #121-BestTimetoBuyandSellStock
- 理解hadoop的Map-Reduce数据流(data flow)
- 学期总结
- springMVC常见面试题
- 【TensorFlow】Windows10 64位下安装TensorFlow
- vmware workstation pro 14 虚拟机无法开启、黑屏的解决方案汇总
- Android so文件引用问题
- ifconfig command not found
- 计算表面静电势_APBS工具