LeetCode122. Best Time to Buy and Sell Stock II

来源:互联网 发布:固定资产标签软件 编辑:程序博客网 时间:2024/05/27 14:13

原题:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/


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


此题将求最大利润改为求最大累计利润;
当当前价格高于先前售出价格时,立即在先前售出价格改为当前价格;
当当前价格小于先前售出价格时,立即在先前售出价格时售出,并于当前买入;
当当前价格小于先前买入价格时,立即在先前售出价格时售出,并于当前买入。


class Solution {public:    int maxProfit(vector<int>& prices) {        int buy = 0, sell = 0, n = 0, sum = 0;        for (int i = 0; i < prices.size(); i++) {            if (prices[i] >= prices[sell]) {                sell = i;                if (i == prices.size()-1) sum += prices[sell] - prices[buy];            }            else if (prices[i] < prices[sell]||prices[buy] > prices[i]) {                sum += prices[sell] - prices[buy];                buy = i;                sell = buy;            }        }        return max(n, sum);    }};

198 / 198 test cases passed.
Status: Accepted
Runtime: 6 ms

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