[LeetCode] Best Time to Buy and Sell Stock II
来源:互联网 发布:智创 软件管理系统 编辑:程序博客网 时间:2024/06/04 00:26
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 max=0;
if(prices==null||prices.length<1)
return 0;
for(int i=0;i<prices.length-1;i++){
for(int j=i+1;j<prices.length-1;j++){
if(prices[j]-prices[i]>max)
max=prices[j]-prices[i];
}
}
return max;
}
}
由于两层for循环,这样做的复杂度是O(n平方),导致超时。由于可以多次买卖,就相当于可以计算没一个后一个数大于前一个数时两者的差值的总和。代码如下:
public class Solution {
public int maxProfit(int[] prices) {
int profit=0;
int start=0;
for(int i=1;i<prices.length;i++){
if(prices[i]>prices[start]){
profit+=prices[i]-prices[start];
}
start=i;
}
return profit;
}
}
但是,又上网百度了下别人做的,说可以采用贪心算法。思路如下:贪心法,本题可以多次买卖股票,从而赚取所有的价格差。因此用贪心法,基本思想是锁定一个低价,然后在价格升到局部最高点(即下一天的价钱就下降了)时候,抛出股票,然后把下一天较低的价钱作为买入,接着计算。要注意最后要处理最后一次的利润。他的代码如下:
public
static
int
maxProfit(
int
[] prices) {
if
(prices.length ==
0
){
return
0
;
}
int
totalProfit =
0
;
int
startIndex =
0
;
int
i;
for
(i=
1
; i<prices.length; i++){
if
(prices[i] < prices[i-
1
]){
totalProfit += prices[i-
1
] - prices[startIndex];
startIndex = i;
}
}
// 要处理最后一次的利润
if
(prices[i-
1
] > prices[startIndex]){
totalProfit += prices[i-
1
] - prices[startIndex];
}
return
totalProfit;
}
- [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
- LeetCode Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- leetcode 61: Best Time to Buy and Sell Stock II
- [LeetCode] Best time to buy and sell a 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
- [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
- Flash Player 漏洞 cve 2014 0497 测试过程
- Updating Maven Project". Unsupported IClasspathEntry kind=4 错误解决方案
- cat、tail、head、tee、grep、wc、sort文件操作和过滤
- 提供一些简单的C++入门程序(提供源代码)
- 认识Spring
- [LeetCode] Best Time to Buy and Sell Stock II
- Linux中的文件描述符
- [转]#、##和__VA_ARGS__的用法
- 详细讲解iOS中的单元测试
- bean的scope属性
- python中的序列
- Codeforces Round #257 (Div. 2) D题:Jzzhu and Cities 删特殊边的最短路
- 百练1088:滑雪 【DP】+【DFS】
- BaseAdapter中重写getview的心得以及发现convertView回收的机制