LeetCode - Best Time to Buy and Sell Stock II

来源:互联网 发布:马库斯斯玛特体测数据 编辑:程序博客网 时间:2024/05/29 07:37

题目描述:

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).


可以进行多次交易,可以在同一天内先卖出后买入,但是最多持有一只股票,那么只要选取所有满足proces[i]-prices[i-1]>0的情况,将所有差值加起来即可,这样就可以利用到所有盈利的机会。

class Solution {public:    int maxProfit(vector<int>& prices) {int n=prices.size();if(n<=1) return 0;    int result=0;        for(int i=1;i<n;i++)        {        if(prices[i]>prices[i-1]) result+=prices[i]-prices[i-1];        }        return result;    }};


0 0