首页 > 其他 > 详细

[LeetCode] 122. Best Time to Buy and Sell Stock II 买卖股票的最佳时间 II

时间:2018-03-09 10:04:29      阅读:193      评论:0      收藏:0      [点我收藏+]

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

给定一个元素代表某股票每天价格的数组,可以买卖股票多次,但不能同时有多个交易,买之前要卖出,求最大利润。

如果当前价格比之前价格高,则可前一天买入,今天卖出,把差值累计到利润中,若明日价更高的话,还可以今日买入,明日再抛出。以此类推,遍历完整个数组后即可求得最大利润。

Java:

public class Solution {
    public int maxProfit(int[] prices) {
        int res = 0;
        for (int i = 0; i < prices.length - 1; ++i) {
            if (prices[i] < prices[i + 1]) {
                res += prices[i + 1] - prices[i];
            }
        }
        return res;
    }
}

Python:

class Solution:
    def maxProfit(self, prices):
        profit = 0
        for i in xrange(len(prices) - 1):
            profit += max(0, prices[i + 1] - prices[i])     
        return profit

C++:

public class Solution {
    public int maxProfit(int[] prices) {
        int res = 0;
        for (int i = 0; i < prices.length - 1; ++i) {
            if (prices[i] < prices[i + 1]) {
                res += prices[i + 1] - prices[i];
            }
        }
        return res;
    }
}

 

类似题目:

[LeetCode] 121. Best Time to Buy and Sell Stock 买卖股票的最佳时间

[LeetCode] 123. Best Time to Buy and Sell Stock III 买卖股票的最佳时间 III

[LeetCode] 188. Best Time to Buy and Sell Stock IV 买卖股票的最佳时间 IV

[LeetCode] 309. Best Time to Buy and Sell Stock with Cooldown 买卖股票的最佳时间有冷却期

  

  

[LeetCode] 122. Best Time to Buy and Sell Stock II 买卖股票的最佳时间 II

原文:https://www.cnblogs.com/lightwindy/p/8531925.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!