LeetCode 122. Best Time to Buy and Sell Stock II
来源:互联网 发布:三年级数学算法 编辑:程序博客网 时间:2024/06/08 04:06
方法1(不可行):
用递归寻找所有可能性 但是这种方法效率太慢 不能通过
空间复杂度 O(n^n)
时间复杂度O(n)
方法2(不可行):
用valley 和peak分别储存 低谷和高峰
最后累计返回值
class Solution {
public int maxProfit(int[] prices) {
int i =0;
int valley=prices[0];
int peak=prices[0];
int maxprices=0;
while(i<prices.length-1){
while(i<prices.length-1 && prices[i]>=prices[i+1])
i++;
valley=prices[i];
while(i<prices.length-1 && prices[i]<=prices[i+1])
i++;
peak=prices[i];
maxprices+=(peak-valley);
}
return maxprices;
}
}
时间复杂度O(n)
空间复杂度O(1)
本想此方法应该能通过 但被系统告知数组索引越界 刚开始不懂 后来分析 大概是i++的部分有问题 如果是倒数第二以及倒数第一 就有越界问题,但是这个是官方给的Solution,贴出来居然是错的 。。 自己试着改了一下 还是发觉不太能搞定。。方法三(ac):
单纯用一个for循环遍历数组,然后判断其中如果prices当前位的值大于前一位的值,累计profit最后return
class Solution {
public int maxProfit(int[] prices) {
int maxprices=0;
for(int i=1;i<prices.length;i++){
if(prices[i]>prices[i-1])
maxprices+=prices[i]-prices[i-1];
}
return maxprices;
}
}
时间复杂度O(n)
空间复杂度O(1)
此方法刚开始写 报错了 仔细看了下后发现 for循环i变量初值赋成了0 这个错误很致命 ,因为这样第一位就没法比较了,所以初值应该赋成1 ,就是说从第二位开始比较 遍历该数组
可能自己基础不太好,很多简单的问题分析上也花了不少时间,还是要多打代码多思考
阅读全文
0 0
- LeetCode 122. 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】122.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 #122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II LeetCode
- [LeetCode]122. 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 122. 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 122. 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 - 122. Best Time to Buy and Sell Stock II
- Java——进程和线程
- linux mysql自动备份shell脚本
- Java——垃圾回收机制
- JavaWeb-Servlet-Properties
- PIL (Python Imaging Library) 教程
- LeetCode 122. Best Time to Buy and Sell Stock II
- C++笔记——继承(代码还有些问题)
- C语言 解一元二次方程,求虚数解:共轭复根
- 剑指offer之把字符串转换成整数
- C++迷一样的对象、引用、const
- RPG游戏引擎开发日志1:理解分析RPG游戏
- css知识点
- Centos7开启SSH服务
- RPG游戏引擎开发日志2:地图坐标转换