码迷,mamicode.com
首页 > 其他好文 > 详细

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

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

标签:ldo   pos   href   python   time   完整   get   des   you   

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

标签:ldo   pos   href   python   time   完整   get   des   you   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!