[Leetcode 122, Medium] Best Time to Buy and Sell Stock II

来源:互联网 发布:端口的作用是什么 编辑:程序博客网 时间:2024/05/15 01:09

Problem:

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

Analysis:


Solutions:

C++:

    int maxProfit(vector<int>& prices)     {    int maxValue = 0;    vector<int> v_profits;    v_profits.push_back(0);    int max_profit = 0;    for(int i = 1; i < prices.size(); ++i)    v_profits.push_back(prices[i] - prices[i - 1]);    for(int i = 0; i < v_profits.size(); ++i)    max_profit += (v_profits[i] > 0 ? v_profits[i] : 0);    return max_profit;    }
Java:


Python:

0 0
原创粉丝点击