Best Time to Buy and Sell Stock

public class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        if(null == prices || prices.length < 1)
            return profit;
        int [] diff = new int[prices.length];
        diff[0] = 0;
        for(int i=1; i<prices.length; i++)
            diff[i] = prices[i] - prices[i-1];
        int temp = 0;
        for(int i=0; i<diff.length; i++){
            if(temp <0)
                temp = diff[i];
            else
                temp += diff[i];
            if(profit < temp)
                profit = temp;
        }
        return profit;
    }
}
本题即为求解一个数组中的最大差值。解题思路是先求出数组的相邻增量数组,转化为求增量数组的连续子数组的最大和问题。

一开始使用两层循环来求解,在leetcode提交时导致Timeout的问题。如下所示(低效算法):

public class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        if(null == prices || prices.length < 1)
            return profit;
        for(int i=0; i<prices.length; i++)
            for(int j=i+1; j<prices.length; j++)
                if(prices[j]-prices[i] > profit)
                    profit = prices[j] - prices[i];
        return profit;
    }
}

Submission Result: Time Limit Exceeded
Last executed input: [10000,9999,9998,9997,9996,9995,9994,9993,9992,9991,9990,9989,9988,9987,9986,9985,9984,9983,9982,9981...]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值