Leetcode122. Best Time to Buy and Sell Stock II

来源:互联网 发布:战舰世界详细数据 编辑:程序博客网 时间:2024/05/19 12:41

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

Subscribe to see which companies asked this question

C++代码:

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

0 0
原创粉丝点击