描述
假设你有一个数组prices,长度为n,其中prices[i]是股票在第i天的价格,请根据这个价格数组,返回买卖股票能获得的最大收益
1.你可以买入一次股票和卖出一次股票,并非每天都可以买入或卖出一次,总共只能买入和卖出一次,且买入必须在卖出的前面的某一天
2.如果不能获取到任何利润,请返回0
3.假设买入卖出均无手续费
数据范围: 0<= n <= 10^5 ,0≤val≤10^4
要求:空间复杂度 O(1),时间复杂度 O(n)
示例1
输入:
[8,9,2,5,4,7,1]
返回值:
5
说明:
在第3天(股票价格 = 2)的时候买入,在第6天(股票价格 = 7)的时候卖出,最大利润 = 7-2 = 5 ,不能选择在第2天买入,第3天卖出,这样就亏损7了;同时,你也不能在买入前卖出股票。
示例2
输入:
[2,4,1]
返回值:
2
示例3
输入:
[3,2,1]
返回值:
0
解法1:双层嵌套
import java.util.*;
public class Solution {
/**
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfit (int[] prices) {
// write code here
int ans = 0;
int len = prices.length;
for(int i = 0; i < len;i++){
for(int j = i+1;j < len;j++){
int tmp_ans = prices[j]-prices[i];
if(tmp_ans>ans){
ans = tmp_ans;
}
}
}
return ans;
}
}
不过因为双层嵌套,时间复杂为O(n)*O(n)
解法2:贪心算法
import java.util.*;
public class Solution {
/**
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfit (int[] prices) {
// write code here
int ans = 0;
int len = prices.length;
int minPrices = Integer.MAX_VALUE;
for(int i = 0; i < len;i++){
if(prices[i] < minPrices){
minPrices = prices[i];
}else if(prices[i]-minPrices>ans){
ans = prices[i]-minPrices;
}
}
return ans;
}
}
时间复杂度为O(n)