LeetCode: Best Time to Buy and Sell Stock II

来源:互联网 发布:关键词快速排名软件 编辑:程序博客网 时间:2024/05/22 04:36

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 min = INT_MAX, profit = 0, total = 0;;        int size = prices.size();        for(int i = 0; i < size; i++)        {            if(prices[i] < min){                min = prices[i];            }            if(prices[i] - min > profit){                profit = prices[i] - min;            }            if(i == size - 1 || prices[i+1] < prices[i])            {                total += profit;                profit = 0;                min = INT_MAX;            }        }        return total;            }};

Round 2:

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


0 0
原创粉丝点击