#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;}
新聞熱點
疑難解答