leecode 解题总结:122. Best Time to Buy and Sell Stock II
来源:互联网 发布:在线视频源码 编辑:程序博客网 时间:2024/05/22 00:23
#include <iostream>#include <stdio.h>#include <vector>using namespace std;/*问题: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 multipletransactions at the same time (ie, you must sell the stock before you buy again).分析:此题的意思是允许多次买入后再抛出股票。每次买入股票前必须先抛出之前买的。举例:0 6 -3 7,可以直接先计算相邻两个元素的差值,将所有大于0的差值累加起来输入:52 4 1 7 1140 6 -3 744 3 2 1输出:12160*/class Solution {public: int maxProfit(vector<int>& prices) { if(prices.empty()){return 0;}int size = prices.size();int diff;int maxSum = 0;for(int i = 1 ; i < size ; i++){diff = prices.at(i) - prices.at(i-1);if(diff > 0){maxSum += diff;}}return maxSum; }};void print(vector<int>& result){if(result.empty()){cout << "no result" << endl;return;}int size = result.size();for(int i = 0 ; i < size ; i++){cout << result.at(i) << " " ;}cout << endl;}void process(){ vector<int> nums; int value; int num; Solution solution; while(cin >> num ) { nums.clear(); for(int i = 0 ; i < num ; i++) { cin >> value; nums.push_back(value); } int result = solution.maxProfit(nums); cout << result << endl; }}int main(int argc , char* argv[]){process();getchar();return 0;}
0 0
- leecode 解题总结:122. Best Time to Buy and Sell Stock II
- leecode 解题总结:121. Best Time to Buy and Sell Stock
- leecode 解题总结:123. Best Time to Buy and Sell Stock III
- leecode 解题总结:309. Best Time to Buy and Sell Stock with Cooldown
- 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] 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】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
- 122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II
- Cent OS 6.5下 vim编辑器推荐配置
- Traffic Sign Recognition
- c/c++中define用法详解及代码示例
- VI编辑器常用指令
- 表格td中的文字居左显示
- leecode 解题总结:122. Best Time to Buy and Sell Stock II
- nginx
- Android实现录屏直播(三)MediaProjection + VirtualDisplay + librtmp + MediaCodec实现视频编码并推流到rtmp服务器
- 三行搞定md5加密
- 虚表(探讨多态的原理)菱形虚拟继承
- iOS动画进阶 - 手摸手教你写ShineButton动画
- Android App引导页
- 改版工具怎么用,你知道吗?
- 网页不收录,都是邀请制惹的祸