leetcode [Best Time to Buy and Sell Stock]//待整理多种解法

class Solution {
    public int maxProfit(int[] prices) {
    	//暴力求解,从后往前找每一个数对应前面的数的差,O(N*N),遇到很长的数据会超时
        int res = 0;
        for(int i = prices.length - 1; i >= 0; i--){
        	for(int j = i - 1; j >= 0; j--){
        		if(prices[i] - prices[j] > res){
        			res = prices[i] - prices[j];
        		}
        	}
        }
        return res;
    }
}

class Solution {
    public int maxProfit(int[] prices) {
    	//因为要寻找最大利益,这就说明了有一个比较更新res的过程,DP
    	//上一种解法是暴力比较,会超时,下面这种解法只用一个循环,比较过程中更新big是一个关键
    	//寻找最大利益需要出售价尽可能高,进价尽可能高,而进价是在往前找,所以更新出售价big的值
        if(prices.length == 0) return 0;
        int res = 0;
        int big = prices[prices.length - 1];
        for(int i = prices.length - 2; i >= 0; i--){
        	if(big - prices[i] > res){//从后往前比较过程中更新最大利益的值
        		res = big - prices[i];
        	}
        	if(prices[i] > big){//从后往前比较过程中也更新出售价big的值
        		big = prices[i];
        	}
        }
        return res;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值