[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
原创粉丝点击