leetcode Best Time to Buy and Sell Stock II

来源:互联网 发布:新网互联域名如何续费 编辑:程序博客网 时间:2024/06/06 12:47

题目

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

题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

一个数组里面存放着一支股票每天的价格。你可以做多次交易,也就是买卖多次。但是你必须在买入之前先把手里的股票卖掉。求最大收益。

分析

  1. 如果今天的价格比前一天低,前一天就不买入;
  2. 如果今天的价格比前一天高,我们就前一天买入,今天卖出。
  3. 遍历数组,将利润相加。

代码

class Solution {public:    int maxProfit(vector<int>& prices) {        int len = prices.size();        if(len <= 0)            return 0;        int max_profit = 0;        int buy_price = prices[0];        for(int i = 0; i < len; i++){            if(prices[i] < buy_price)                buy_price = prices[i];//今天比之前的价格低,相当于前一天没买。            if(prices[i] > buy_price){                max_profit += (prices[i] - buy_price);                buy_price = prices[i];//并不代表着一定会买入,取决于以后的价格。            }        }        return max_profit;    }};
0 0
原创粉丝点击