Leetcode Best Time to Buy and Sell Stock II

来源:互联网 发布:美国私立高中排名知乎 编辑:程序博客网 时间:2024/05/21 14:53

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


代码如下:

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


阅读全文
0 0
原创粉丝点击