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