数据结构与算法
双指针、回溯剪枝、图论与搜索
🎨 视觉封面LeetCode Best Time to Buy and Sell Stock II
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 实现
'''
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版本的样例
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;
}
所有代码开源上传至 GitHub:yummy-code 仓库 · GESP 专题站:GESP WIKI
欢迎加入:C++ GESP/CSP 考级答疑群(688906745) 与 Java/Python交流群(982860385),点击可直接加群。
猜你想读 · 相关文章推荐
LeetCode Minimum Depth of Binary Tree
Problem Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest lea...
LeetCode Path Sum
Problem Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For...
LeetCode Path Sum II
Problem Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum...
OneCoder (lihongzheshuai)
一个中年人的自留地,记录学习 C++、GESP/NOI、Java、Python 与算法架构的心得体会。本站唯一网址:coderli.com