Best Time to Buy and Sell Stock II
来源:互联网 发布:电影天堂软件 编辑:程序博客网 时间:2024/06/16 10:02
Say you have an array for which the ith element is the price of a given stock on dayi.
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).
题目解析:
(1)股票购买的原则:低买高卖。
比如说3 2 1 4 5 6 3,那我们在1的时候买,在6 的时候卖出去。
(2)不过编程的时候要注意一些边界条件。
例如
1、1 1 1 1 1
2、4 3 2 1 1
3、1 2 3 4 5
等特殊序列,以及不要数组越界。
#include <iostream>#include <vector>using namespace std;int maxProfit(vector<int> &prices) {int length = prices.size();int buyPrice = 0;int sellPrice = 0;int profit = 0;for(int i=0;i<length-1;i++){if(prices[i] <= prices[i+1]){buyPrice = prices[i];}else{continue;}while(i<length-2 && prices[i] <= prices[i+1]){i++;}if(prices[i] > prices[i+1]){sellPrice = prices[i];profit = profit + sellPrice - buyPrice;continue;}if(i==length-2){if(prices[i] <= prices[i+1]){sellPrice = prices[i+1];profit = profit + sellPrice - buyPrice;i++;continue;}}}return profit;}int main(void){vector<int> prices;prices.push_back(5);prices.push_back(2);prices.push_back(3);prices.push_back(2);prices.push_back(6);prices.push_back(6);prices.push_back(2);prices.push_back(9);prices.push_back(1);prices.push_back(0);prices.push_back(7);prices.push_back(4);prices.push_back(5);prices.push_back(0);cout << "The Profit is " << maxProfit(prices) << endl;system("pause");return 0;}
0 0
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- Leetcode: Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- LeetCode : Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- leetcode 61: Best Time to Buy and Sell Stock II
- [LeetCode] Best time to buy and sell a stock II
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- 【leetcode】Best Time to Buy and Sell Stock II
- LeetCode - Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- LeetCode之Best Time to Buy and Sell Stock II
- [LeetCode]Best Time to Buy and Sell Stock II
- reactor和proactor模式
- Android中几种图像特效处理
- Android WebView 安全漏洞
- Hive学习之自定义函数(UDF)
- Android与JavaScript方法相互调用
- Best Time to Buy and Sell Stock II
- 在protobuf中使用python的extension
- 3 2 低功耗Demo
- codeforces 265 D. Restore Cube
- 搭建Mantis 缺陷管理系统
- DFS PKU 1979
- 如何在(Linux mint)ubuntu中安装chrome
- Android 4.2 关于GlowPadView的说明
- ctex表格实例——多行多列合并