先看题目
点击查看题目来源
这个题目有两种解法
1、暴力法
public class Solution {
public int maxProfit(int prices[]) {
int length = prices.length;
int max = 0;
for (int i = 0; i < length ; i++) {
for (int j = i ; j < length ; j++) {
if(prices[i] - prices[j] <=0){
max = Math.max(max,prices[j] - prices[i]);
}
}
}
return max ;
}
}
毫无疑问,时间复杂度为n²,offer成功理我越来越远
第二种方法,简单的动态规划,只需遍历一次
class Solution {
public int maxProfit(int[] prices) {
int length = prices.length;
if(length == 0 || prices == null){
return 0;
}
int max = 0;
int min = prices[0];
for(int i = 1 ;i<length;i++){
if(prices[i] <= min){
min = prices[i];
}else{
max = Math.max(max,prices[i] - min);
}
}
return max;
}
}
只需要执行一次,时间复杂度为n
下面来详细解释这个算法的具体实现
1、首先看是否数组为空,如果为空直接返回
int length = prices.length;
if(length == 0 || prices == null){
return 0;
}
2、找出一个最小值的对照变量,取数组中的第一个数为最小值,然后在每一次for循环中进行比较,如果找出比他更小的数,那么让最小的数赋值给min,因为要找出的是最大利润,并且是顺序遍历,所以当后面有更大的数时,相比第一次的min,肯定重新赋值之后的min值所获得的利润最大,这个时候记录当前最大值,再次进行遍历,当再次找到更小的min值时,重新赋值,但是当前的max值仍然是前面的数所记录的最大差值,也就是最大利润数,举个例子,当当前数组为[7,5,2,9,1,6]时,当min=2时,往后接着遍历时,最大利润max=9-2=7,随后min=1,再往后遍历时,到最后一个下标的位置,此时的利润值为6-1=5,但是在上一个数中max=7,并且让max作为返回值,所以即是最大利润数,当然,当行9和6的下标交换位置时,最大利润max=9-1=8,不会出现错误。
int max = 0;
int min = prices[0];
for(int i = 1 ;i<length;i++){
if(prices[i] <= min){
min = prices[i];
}else{
max = Math.max(max,prices[i] - min);
}
}
return max;
继续加油。
剑指offer。