LeetCode122. Best Time to Buy and Sell Stock II
来源:互联网 发布:智能电视机网络电视机 编辑:程序博客网 时间:2024/05/28 04:55
这两周开始接触贪心算法,顾名思义就是使其利益最大化了。先选一道最简单的相关题目来练练手。
LeetCode122. Best Time to Buy and Sell Stock II
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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
意思即是:假设有一个数组,它的第i个元素是一个给定的股票在第i天的价格。设计一个算法来找到最大的利润。你可以完成尽可能多的交易(多次买卖股票)。然而,你不能同时参与多个交易(你必须在再次购买前出售股票)。其实思路很简单,要事利益最大化,那便是不能放过每个可以赚到money的机会。只要相间的两次股票有可以赚的差价,那就把它放入利润当中。
代码如下:
class Solution {public: int maxProfit(vector<int> &prices) { int l = prices.size(); if(l == 0) return 0; int money = 0; int buy = prices[0]; int last = prices[0]; for(int i = 1; i < l; i ++) { if(prices[i] < last) { money += (last - buy); buy = prices[i]; } last = prices[i]; } money += (last - buy); return money; }};
阅读全文
0 0
- leetcode122---Best Time to Buy and Sell Stock II
- LeetCode122:Best Time to Buy and Sell Stock II
- leetcode122 Best Time to Buy and Sell Stock II
- LeetCode122. Best Time to Buy and Sell Stock II
- leetcode122 Best Time to Buy and Sell Stock II
- Leetcode122. Best Time to Buy and Sell Stock II
- leetcode122.[DP] Best Time to Buy and Sell Stock II
- LeetCode122—Best Time to Buy and Sell Stock II
- leetcode122. Best Time to Buy and Sell Stock II
- leetcode122~Best Time to Buy and Sell Stock II
- LeetCode122. Best Time to Buy and Sell Stock II题解
- LeetCode122 Best Time to Buy and Sell Stock II
- Leetcode122. Best Time to Buy and Sell Stock II
- LeetCode122. Best Time to Buy and Sell Stock II
- LeetCode122. Best Time to Buy and Sell Stock II
- LeetCode122. Best Time to Buy and Sell Stock II
- LeetCode122——Best Time to Buy and Sell Stock II
- Leetcode122 - Best Time to Buy and Sell Stock II (dp)
- Spring系列——@RequestMapping
- 怎么在linux下打包免安装的QT程序。
- 数据结构导论-不得不知的基础
- SIFT--方向分配
- 数字个数依次叠加 s=a+aa+aaa+aaaa+aa...a
- LeetCode122. Best Time to Buy and Sell Stock II
- C++之求取vector中三个元素和和给定元素最接近的值(15)---《那些奇怪的算法》
- 详解malloc/free和new/delete
- 2017.10.22开学第八周周总结
- Android中的内存管理机制
- Calling Circles UVA
- JSP结构、生命周期
- Intellij Idea 2017 设置Eclipse快捷键风格
- mysql外键的操作