OneCoder Avatar
OneCodercoderli.com · 937 篇博文
🧮 Algo

数据结构与算法

双指针、回溯剪枝、图论与搜索

🎨 视觉封面

LeetCode Best Time to Buy and Sell Stock II

📅 2017-12-06·✍️ onecode·计算中...·⏱️ 5 分钟
#LeetCode#Python

Problem

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

上一个问题的变形,即求累计利润的最大值。就是按顺序相减的和。

Python 实现

PYTHON

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

#author li.hzh

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if prices is None or len(prices) <= 1:
            return 0
        buy = sell = prices[0]
        profit = 0
        for index in range(1,len(prices)):
            if prices[index] < sell:
                profit += (sell - buy)
                buy = sell = prices[++index]
            else:
                sell = prices[index]
        profit += (sell - buy)
        return profit


print(Solution().maxProfit([7, 1, 5, 3, 6, 4]))
print(Solution().maxProfit([7, 6, 4, 3, 1]))
print(Solution().maxProfit([7, 6, 7, 3, 5]))

分析

并不是最简代码,其实有个很简单的思路。就是遍历,如果i+1 > i 的值,就相减。如此累计即可。代码非常简洁。粘一个Java版本的样例

JAVA
public class Solution {
public int maxProfit(int[] prices) {
    int total = 0;
    for (int i=0; i< prices.length-1; i++) {
        if (prices[i+1]>prices[i]) total += prices[i+1]-prices[i];
    }
    
    return total;
}
💡 OneCoder 资源指引

所有代码开源上传至 GitHub:yummy-code 仓库 · GESP 专题站:GESP WIKI

🤝 技术交流与答疑

欢迎加入:C++ GESP/CSP 考级答疑群(688906745)Java/Python交流群(982860385),点击可直接加群。

📚

猜你想读 · 相关文章推荐

OneCoder

OneCoder (lihongzheshuai)

一个中年人的自留地,记录学习 C++、GESP/NOI、Java、Python 与算法架构的心得体会。本站唯一网址:coderli.com

💬 读者留言与交流

0 条讨论
✨ 支持 Markdown 语法格式
还没有留言,快来成为第一个讨论者吧!