螺竹编程
发布于 2024-05-26 / 8 阅读
0

算法题/股票交易:买卖股票的最佳时间之多次交易

题目

给定一个数组prices,它的第1个元素prices[i]表示一支给定股票第i天的价格。

设计一个算法来计算你所能获得的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回0.

注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

示例:

输入:[7,1,5,3,6,4]
输出:7
解释:在第2天(股票价格为1)的时候买入,在第3天(股票价格为5)的时候卖出,这笔交易的利润为4。随后,在第4天(股票价格为3)的时候买入,在第5天(股票价格为6)的时候卖出,这笔交易的利润为3。

题解

Java

public class Solution{
    public static void main(String[] args){
        int[] array = {7, 1, 5, 3, 6, 4};
        maxProfit(array);
    }
    public static int maxProfit(int[] prices){
        int result=0;
        for(int buy=0;buy<prices.length;buy++){
            for(int sell=buy+1;sell<prices.length;sell++){
                result=max(result,maxProfit(prices[sell+1])+
            }
        }
    }
}

JavaScript

function maxProfit(prices) {
    let result = 0;
    for (let buy = 0; buy < prices.length; buy++) {
        for (let sell = buy + 1; sell < prices.length; sell++) {
            result = Math.max(result, prices[sell] - prices[buy]);
        }
    }
    return result;
}

const array = [7, 1, 5, 3, 6, 4];
console.log(maxProfit(array));

Python

def maxProfit(prices):
    result = 0
    for buy in range(len(prices)):
        for sell in range(buy + 1, len(prices)):
            result = max(result, prices[sell] - prices[buy])
    return result

array = [7, 1, 5, 3, 6, 4]
print(maxProfit(array))

Go

package main

import "fmt"

func maxProfit(prices []int) int {
    result := 0
    for buy := 0; buy < len(prices); buy++ {
        for sell := buy + 1; sell < len(prices); sell++ {
            if prices[sell]-prices[buy] > result {
                result = prices[sell] - prices[buy]
            }
        }
    }
    return result
}

func main() {
    array := []int{7, 1, 5, 3, 6, 4}
    fmt.Println(maxProfit(array))
}