《leetcode》best-time-to-buy-and-sell-stock-i-ii-iii

本文探讨了不同限制条件下股票交易最大利润的算法实现。包括无限次交易、仅能交易一次及最多两次的情况,并提供具体代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述1

Say you have an array for which the i th 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 class Solution {
    public int maxProfit(int[] prices) {
        int maxProfile=0;
        for(int i=0;i<prices.length-1;i++){
            if(prices[i]<prices[i+1]){
                maxProfile+=prices[i+1]-prices[i];
            }
        }
        return maxProfile;
    }
}

题目描述2

Say you have an array for which the i th 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.

解析:题目表示最多只能买卖一次

public class Solution {
    public int maxProfit(int[] prices) {
       int maxProfile=0;
       for(int i=0;i<prices.length;i++){
           for(int j=i+1;j<prices.length;j++){
               maxProfile=maxProfile>(prices[j]-prices[i])?maxProfile:(prices[j]-prices[i]);
           }
       }

       return maxProfile;
    }
}

题目描述3(较为复杂些了

Say you have an array for which the i th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

解析:最多买卖两次,可以以i为分界线,然后在i的左侧搜索最大的利润,在i的右侧也搜索最大的利润,最后算总的利润。

测试用例
输入:
[6,1,3,2,4,7]

输出:
7

这里写图片描述

import java.util.*;
public class Solution {
    public int maxProfit(int[] prices) {
        int maxProfile=0;
        int length=prices.length;
        for(int i=0;i<length;i++){
            int leftMax=0,rightMax=0;
            for(int j=0;j<i;j++){//搜索左侧的最大利润
                for(int k=j+1;k<=i;k++){
                    int temp =prices[k]-prices[j];
                    leftMax=leftMax>temp?leftMax:temp;
                }
            }

            for(int j=i+1;j<length;j++){//搜索右侧的最大利润
                for(int k=j+1;k<length;k++){
                    int temp =prices[k]-prices[j];
                    rightMax=rightMax>temp?rightMax:temp;
                }
            }
            if(leftMax+rightMax>maxProfile){
                maxProfile=leftMax+rightMax;
            }
        }
        return maxProfile;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值