leetcode做题总结,题目Best Time to Buy and Sell Stock 2012/10/30
来源:互联网 发布:知识产权 淘宝 编辑:程序博客网 时间:2024/03/28 21:40
之前没想出来,今天忘了是看算法导论还是另一本算法书讲到了最大子序列,正好就拿这道题做例子,一种方法是二分递归两边的最大子序列,然后再合并,计算穿过中界线的最大序列进行递归求最大值。还有一种更好的方法是类似于GAS 那道题,求出变化量数组,然后相加,如果总和为负,则序列从新开始。这样只需O(n)的时间复杂度。
public int maxProfit(int[] prices) { int num = prices.length; if(num==0||num==1)return 0; int[] pr = new int[num-1]; for(int i=0;i<num-1;i++){ pr[i]=prices[i+1]-prices[i]; } int max=0; int thi=0; for(int i=0;i<num-1;i++){ thi=thi+pr[i]; if(thi>max) max=thi; if(thi<0) thi=0; } return max; }
Update 2015/08/21: 思路同上,只是优化了一下
public class Solution { /** * @param prices: Given an integer array * @return: Maximum profit */ public int maxProfit(int[] prices) { // write your code here int len = prices.length - 1; for (int i = 0; i< len; i++){ prices[i] = prices[i + 1] - prices[i]; } int global = 0; int local = 0; for (int i = 0; i< len; i++){ local = local + prices[i]; if (local < 0){ local = 0; } global = Math.max(global, local); } global = Math.max(global, local); return global; }}
0 0
- leetcode做题总结,题目Best Time to Buy and Sell Stock 2012/10/30
- leetcode题目:Best Time to Buy and Sell Stock III
- [Leetcode] 总结--Best Time to Buy and Sell Stock
- LeetCode 30 Best Time to Buy and Sell Stock II
- 【LeetCode】Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock做题笔记
- [Leetcode刷题总结系列][Dynamic programming] 121. Best time to buy and sell stock
- [LeetCode] [LeetCode]Best Time to Buy and Sell Stock
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock
- LeetCode Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- Leetcode: Best time to buy and sell a stock I
- Leetcode: Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock
- C++ protected的访问权限问题
- C++中string总结
- Dalvik虚拟机与java虚拟机的异同
- hdu 4825
- Pat(Advanced Level)Practice--1081(Rational Sum)
- leetcode做题总结,题目Best Time to Buy and Sell Stock 2012/10/30
- 设计模式-适配器(Adaper)模式
- 关于dup和dup2函数的重定向与还原
- HDU 2163 Palindromes
- 集合(Map练习)
- 最短路径Ⅰ—Dijkstra算法
- Java多态
- JSP基础语法(章节摘要)
- 1407282112-hd-Max Num.cpp