leetcode - Best Time to Buy and Sell Stock II
2018-01-30 20:24
435 查看
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).
解释:买卖股票,这次运行多次交易,但要求是在买股票之前需要把股票都卖掉。
Solve:
用贪心法求解,如果后一天价格高于前一天价格就卖出,这样能得到最大收益(单天可卖出可买进 两者不干扰)
(时间复杂度O(n),AC-2ms)public int maxProfit(int[] prices) {
if(prices==null||prices.length<1){
return 0;
}
int sum=0;
for(int i=0;i<prices.length-1;i++){
if(prices[i+1]>prices[i]){//后一天价格高于前一天就卖出
sum+=prices[i+1]-prices[i];
}
}
return sum;
}后记:单天可卖出买进这个条件也挺重要的。
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).
解释:买卖股票,这次运行多次交易,但要求是在买股票之前需要把股票都卖掉。
Solve:
用贪心法求解,如果后一天价格高于前一天价格就卖出,这样能得到最大收益(单天可卖出可买进 两者不干扰)
(时间复杂度O(n),AC-2ms)public int maxProfit(int[] prices) {
if(prices==null||prices.length<1){
return 0;
}
int sum=0;
for(int i=0;i<prices.length-1;i++){
if(prices[i+1]>prices[i]){//后一天价格高于前一天就卖出
sum+=prices[i+1]-prices[i];
}
}
return sum;
}后记:单天可卖出买进这个条件也挺重要的。
相关文章推荐
- Best Time to Buy and Sell Stock II (LeetCode)
- LeetCode122:Best Time to Buy and Sell Stock II
- leetcode 日经贴,Cpp code -Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock II
- [LeetCode]122 Best Time to Buy and Sell Stock II
- LeetCode 122: Best Time to Buy and Sell Stock II
- (LeetCode)Best Time to Buy and Sell Stock II
- LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
- leetcode--Best Time to Buy and Sell Stock i ii iii
- Leetcode 122 Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- 【leetcode刷题笔记】Best Time to Buy and Sell Stock II
- leetcode - Best Time to Buy and Sell Stock II
- leetcode - Best Time to Buy and Sell Stock II
- [leetcode代码]Best Time to Buy and Sell Stock II
- LeetCode122:Best Time to Buy and Sell Stock II
- 【LeetCode】 best-time-to-buy-and-sell-stock-i ii iii iv
- leetcode_122——Best Time to Buy and Sell Stock II(贪心算法)
- Leetcode: Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II leetcode java