leetcode--Best Time to Buy and Sell Stock II

来源:互联网 发布:java tcp编程实例 编辑:程序博客网 时间:2024/06/10 07:19

1问题

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

2.分析

可以进行多次交易,但不能有两个交易是同时进行的,即卖出一个后才能买进新的。

贪心策略:要尽可能进行最多的交易,每次交易达到最大收益时卖出,每当价钱比上一天的价钱低时,以上一天的价钱卖出,以当天的价钱买进开始新的交易。


3.实现

class Solution {public:    int maxProfit(vector<int>& prices) {        int min,profit=0,totalProfit=0,last=INT_MAX;        for(int i=0;i<prices.size();++i)        {            if(prices[i]<=last)            {                min = prices[i];                totalProfit += profit;                profit = 0;            }                        if(prices[i]-min>profit)                profit = prices[i]-min;            last = prices[i];        }        totalProfit += profit;        return totalProfit;    }};


0 0