Clever Castle
274 words
1 minutes
LeetCode 343,122 整数拆分求积 递增区间寻找

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

已知物品每天的价格,讨论通过买卖可以赚到的最多利润。卖之前必须买,再一次买之前必须卖掉。

寻找所有递增区间,区间尾头之差即单次利润。

public int maxProfit(int[] prices) {
    int maxProfit=0;
    for(int i=0;i<prices.length;){
        int plus=1;
        int flag=0;

        while (i+plus<prices.length&&prices[i+plus-1]<prices[i+plus]){
            plus+=1;
            flag=1;
        }
        if(flag==1){
            maxProfit+=prices[i+plus-1]-prices[i];
        }
        i+=plus;
    }
    return maxProfit;
}

343 Integer Break#

给一个自然数n,把它拆分为若干个数的和,记这若干个数的乘积为M,求M的最大值。

方法:尽可能将这个数拆分成3,原因下方解释。

public int integerBreak(int n) {
    if(n==2){
        return 1;
    }
    if(n==3){
        return 2;
    }
    if(n==4){
        return 4;
    }
    int mod=n%3;
    int res=0;
    res=(int)Math.pow(3,n/3);
    System.out.println(res);
    if(mod==1){
        res=res/3*4;
        return res;
    }

    if(mod==2){
        res=res*2;
        return res;
    }
    return res;
}

证明#

因为有不等式 x1x2x3x4...xkkx1x2x3x4...xkk\sqrt[k]{x_1x_2x_3x_4...x_k}\leq \frac{x_1x_2x_3x_4...x_k}{k}

n=x1+x2+x3+x4+x5+...+xkn=x_1+x_2+x_3+x_4+x_5+...+x_kP=x1x2x3x4x5+...xkP=x_1x_2x_3x_4x_5+...x_k

所以有P(nk)kP \leq (\frac{n}{k})^k

LeetCode 343,122 整数拆分求积 递增区间寻找
https://blog.ivyxjc.com/posts/leetcode-122-343/
Author
ivyxjc
Published at
2016-04-21