看完书上不是premium的题了,正式开始刷题。
先来这个高频的买卖股票的题
Question
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
此题看似简单,但其实是在找一组数组里面最大差值,且最大值在最小值出现之后
在网上找到了相关的算法解答
http://www.geeksforgeeks.org/maximum-difference-between-two-elements/
一开始最简单的是brute force方法,但是O(N^2) OJ显然不满意,说超时了
于是第一种算法
solution 1
O(N), O(1)
遍历一遍,每次对比maxProfit和最小值,做相应改变
public class Solution {
//observe min and maxProfit while traverse the array
public int maxProfit(int[] prices) {
if(prices.length <= 1) return 0;
int min = prices[0]; int maxProfit = 0;
for(int i = 1; i < prices.length; i++){
if(prices[i]-min > maxProfit) maxProfit = prices[i]-min;
if(prices[i] < min) min = prices[i];
}
return maxProfit;
}
}
Solution 2
runtime O(n), space O(n)
把每个相邻价格的差存成array,然后如果一直增加就加起来,来找到最大profit
public class Solution {
//observe min and maxProfit while traverse the array
public int maxProfit(int[] prices) {
if(prices.length <= 1) return 0;
int[] diff = new int[prices.length-1];
//find each adjacent diff
for(int i = 0; i < prices.length-1; i++){
diff[i] = prices[i+1] - prices[i];
}
int maxDiff = diff[0] >= 0 ? diff[0] : 0;
for(int i = 1; i < prices.length-1; i++){
if(diff[i-1] > 0) diff[i] += diff[i-1];
if(diff[i] > maxDiff) maxDiff = diff[i];
}
return maxDiff;
}
}
把之前的简化一些,可以变成space为O(1)的,如下:
public class Solution {
//observe min and maxProfit while traverse the array
public int maxProfit(int[] prices) {
if(prices.length <= 1) return 0;
int maxDiff = (prices[1] - prices[0] >= 0) ? prices[1] - prices[0] : 0;
int diff = maxDiff; int currSum = maxDiff;
for(int i = 1; i < prices.length-1; i++){
diff = prices[i+1] - prices[i];
if(currSum > 0) currSum += diff;
else currSum = diff;
if(currSum > maxDiff) maxDiff = currSum;
}
return maxDiff;
}
}