[LeetCode]122. Best Time to Buy and Sell Stock II(最佳买卖时间 II)
来源:互联网 发布:男生背包推荐知乎 编辑:程序博客网 时间:2024/04/20 16:47
122. 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天给定股票的价格。
设计一个算法来找到最大的利润。 你可以根据需要完成尽可能多的交易(即,买一次卖一次,多次出售股票)。 但是,您可能不会同时从事多个交易(即,您必须在再次购买之前出售股票)
思路:
- 遍历数组
- 只要后面价格高于前面,差值就加到利润上
- 最终得到最大利润
- 例如:{2, 8, 6, 9} 利润最高是9,Profit = (8-2) + (9-6)
- 例如:{5, 1, 2, 4, 6} 利润最高是5,Profit = (2-1) + (4-2)+ (6-4)
代码如下:
#include <iostream>#include <vector>using namespace std;class Solution {//求股票最大收益,每次只能持有一股,卖必须在买之后public: int maxProfit(vector<int>& prices) { if(prices.size() == 0) return 0; int MaxProfit = 0; for(int i=0; i< prices.size()-1; i++){//i+1 最大为n-1,n为数组长度 if(prices[i] < prices[i+1]) MaxProfit += prices[i+1] - prices[i];//更新最大利益 } /* for(int i=1; i< prices.size(); i++){ if(prices[i] > prices[i-1]) MaxProfit += prices[i] - prices[i-1];//更新最大利益 } */ return MaxProfit; }};int main(){ Solution a; int A[4] = {2, 8, 6, 9}; vector<int> prices(A, A+4); cout << "股票近期行情:"; for(int i=0; i< prices.size(); i++){ cout << prices[i] << " "; } cout << endl; cout << "最大收益:" << a.maxProfit(prices) << endl; return 0;}
点击查看LeetCode官方解决方案
0 0
- [LeetCode]122. Best Time to Buy and Sell Stock II(最佳买卖时间 II)
- 122. Best Time to Buy and Sell Stock II 最佳买卖股票的时间
- Best Time to Buy and Sell Stock II 最佳时间买入卖出股票(多次买卖)@LeetCode
- LeetCode OJ 之 Best Time to Buy and Sell Stock II (买卖股票的最佳时间 2)
- leetcode 122. Best Time to Buy and Sell Stock II 股票买卖最佳时间(二)
- Best Time to Buy and Sell Stock II 买卖股票最好的时间II
- LeetCode 122. Best Time to Buy and Sell Stock II
- [Leetcode] 122. Best Time to Buy and Sell Stock II
- [leetcode] 122.Best Time to Buy and Sell Stock II
- 【leetcode】122.Best Time to Buy and Sell Stock II
- 【LeetCode】122.Best Time to Buy and Sell Stock II
- [leetcode] 122. Best Time to Buy and Sell Stock II
- LeetCode #122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II LeetCode
- [LeetCode]122. Best Time to Buy and Sell Stock II
- Leetcode 122. Best Time to Buy and Sell Stock II
- leetcode 122. Best Time to Buy and Sell Stock II
- LeetCode 122. Best Time to Buy and Sell Stock II
- L2-001. 紧急救援
- cassandra-driver-python
- L2-002. 链表去重
- java之简单的Callback使用总结
- L2-003. 月饼
- [LeetCode]122. Best Time to Buy and Sell Stock II(最佳买卖时间 II)
- 10.Django入门:高级教程-编写Django的第一个补丁
- L2-004. 这是二叉搜索树吗
- L2-005. 集合相似度
- L2-006. 树的遍历
- L2-007. 家庭房产
- Codeforces Beta Round #9 (Div. 2 Only):B
- L2-008. 最长对称子串
- JavaScript学习-location对象