leetcode题解-121. Best Time to Buy and Sell Stock && 122. Best Time to Buy and Sell St && 66. Plus One

今天的两道题都很简单,就直接在一篇博客里进行记录即可。
首先说一下66. Plus One这道题目:

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

也就是将数字表示为数组的形式,然后求其加1的结果。题目思路很清楚,主要是判断相应的数字位是否为9即可。如果一直有连续的9出现,则将其置为0,否则+1返回结果。需要注意的是如果最高位仍是9,则需要补一位,置为1。比如99–>100。代码入下所示:

    public int[] plusOne(int[] digits) {
        for(int j=digits.length-1; j>=0; j--){
            if(digits[j] != 9){
                digits[j] += 1;
                return digits;
            }else
                digits[j] = 0;
        }
        int [] res = new int[digits.length +1];
        res[0] = 1;
        return res;
    }

下面说第二题:121. Best Time to Buy and Sell Stock。题目如下:

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.

Example 1: Input: [7, 1, 5, 3, 6, 4] Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2: Input: [7, 6, 4, 3, 1] Output: 0
In this case, no transaction is done, i.e. max profit = 0.

其实题目就是给一个商品价格变动数组,让你找到最合适的买入卖出时间。理解题目之后我们只需要使用一个left指针记录当前的最低价格,使用max记录当前位置的最大收益即可。然后遍历所有数据,代码入下:

    public int maxProfit(int[] prices) {
        int left = 0, max = 0;
        for(int i=0; i<prices.length; i++){
            if(prices[i] > prices[left])
                max = Math.max(max, prices[i] - prices[left]);
            else
                left = i;
        }
        return max;
    }

接下来说第三题122. Best Time to Buy and Sell Stock II。题目如下:

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

本题在121的基础上进行了扩展,可以进行多次交易,求最大利润。但是相比之下,缕清思路之后我们会发现题目反而变简单了。因为我们只需将相邻元素相减如果大于零求和即可。代码入下:

    public int maxProfit(int[] prices) {
        int len = prices.length;
        int profit = 0;
        for(int i = 1; i < len ; i++){
            if(prices[i]-prices[i-1] <= 0){
                continue;
            }
            profit += prices[i]-prices[i-1];
        }
        return profit;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值