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).
public class Solution { public int maxProfit(int[] prices) { if (prices.length <= 1) { return 0; } int i = 0; int res = 0; while (i < prices.length-1) { while (i+1<prices.length && prices[i+1]<prices[i]) { i++; } int buy = i; i++; while (i<prices.length && prices[i]>prices[i-1]) { i++; } int sell = i-1; res += prices[sell]-prices[buy]; } return res; } }
相关推荐
《最佳买卖股票时机II》是LeetCode中的一道经典编程题目,主要涉及动态规划和数组操作的知识点。在这个问题中,我们被赋予一个整数数组`prices`,表示某支股票每天的价格。任务是找到在允许进行多次交易的情况下,...
java java_leetcode题解之Best Time to Buy and Sell Stock II.java
java java_leetcode题解之Best Time to Buy and Sell Stock with Cooldown
java java_leetcode题解之Best Time to Buy and Sell Stock IV.java
java java_leetcode题解之Best Time to Buy and Sell Stock III.java
java java_leetcode题解之Best Time to Buy and Sell Stock I.java
java lru leetcode leetcode-java leetcode刷题笔记 已做题目列表 1.Two Sum 3.Longest Substring ...121.Best Time to Buy and Sell Stock 122.Best Time to Buy and Sell Stock II 123.Best Time ...II
- Best Time to Buy and Sell Stock II:不限制交易次数,寻找最大利润。 - Best Time to Buy and Sell Stock III:存在多日限制交易,最多两次交易。 - Best Time to Buy and Sell Stock IV:与前三者不同,可能...
II (Easy) 可多次交易,找总最大收益 for i in range(1,len(prices): profit+=prices[i]-prices[i-1] if prices[i]-prices[i-1]>0 Best Time to Buy and Sell Stock III (Hard) 最多两次交易(同理固定次数的多次)...
Best Time to Buy and Sell Stock 122 买卖股票的最佳时机 Ⅱ Best Time to Buy and Sell StockⅡ 123 买卖股票的最佳时机 Ⅲ Best Time to Buy and Sell StockⅢ 188 买卖股票的最佳时机Ⅳ Best Time to Buy and ...
python python_leetcode题解之122_Best_Time_to_Buy_and_Sell_Stock_II
javascript js_leetcode题解之122-best-time-to-buy-and-sell-stock-ii.js
python python_leetcode题解121_Best_Time_to_Buy_and_Sell_Stock
第二个问题“Best Time to Buy and Sell Stock II”(122题),题目条件相同,但允许进行多笔交易。在一次交易中,买入后再卖出才算是完成了一笔交易,且不能同时买入多股股票。此问题可以用贪心算法解决,即遍历...
javascript js_leetcode题解之121-best-time-to-buy-and-sell-stock.js
python python_leetcode题解之123_Best_Time_to_Buy_and_Sell_Stock_III
javascript js_leetcode题解之123-best-time-to-buy-and-sell-stock-iii.js
7. **122.py** - 可能是LeetCode的122题,"Best Time to Buy and Sell Stock II"(买卖股票的最佳时机II),这是一道关于动态规划或贪心策略的题目,用于找出股票交易的最佳策略。 8. **156.py** - 这可能是...
- **股票买卖问题**:如LeetCode上的题目《Best Time to Buy and Sell Stock II》,通过贪心策略,每次遇到股价低于之前最低价时买入,遇到高于当前价格时卖出,可以实现利润的最大化。 - **零钱找零问题**:...