[LeetCode] Best Time to Buy and Sell Stock II

来源:互联网 发布:智创 软件管理系统 编辑:程序博客网 时间:2024/06/04 00:26
题目要求如下:

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).

一开始没明白题意,百度了下,原来是要求求出数组中最大的整数差。

Java代码如下:

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

由于两层for循环,这样做的复杂度是O(n平方),导致超时。由于可以多次买卖,就相当于可以计算没一个后一个数大于前一个数时两者的差值的总和。代码如下:

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

但是,又上网百度了下别人做的,说可以采用贪心算法。思路如下:贪心法,本题可以多次买卖股票,从而赚取所有的价格差。因此用贪心法,基本思想是锁定一个低价,然后在价格升到局部最高点(即下一天的价钱就下降了)时候,抛出股票,然后把下一天较低的价钱作为买入,接着计算。要注意最后要处理最后一次的利润。他的代码如下:

 publicstaticint maxProfit(int[] prices) {
        if(prices.length == 0){
            return0;
        }
        inttotalProfit = 0;
        intstartIndex = 0;
        inti;
         
        for(i=1; i<prices.length; i++){
            if(prices[i] < prices[i-1]){
                totalProfit += prices[i-1] - prices[startIndex];
                startIndex = i;
            }
        }
        // 要处理最后一次的利润
        if(prices[i-1] > prices[startIndex]){
            totalProfit += prices[i-1] - prices[startIndex];
        }
         
        returntotalProfit;
    }



0 0
原创粉丝点击