C语言刷题 LeetCode 30天挑战 (五)贪心算法

//Best Time to Buy and Sell Stockl
//Say you have an array for which the ith element is the price of a given stock on day i.
//Desian an algorithm to find the maximum profit, You mav complete as many transactions as you like lle.. 
//buy one and sell one share othe stock multiple times)
//Note: You may not engage in multiple transactions at the same time (i.., you must sell the stock before you buy again
//Example 1:
//Input:[7,1,5,3,6,4]
//Output:7
//Explanation: Buyon day2(price=1)and sell on day 3(price = 5),profit = 5-1 = 4.
//Then buy on day4(price=3)and sell on day5(price =6),profit =6-3 = 3.
//Example 2:
//Input:[1,2,3,4,5]
//0utput:4
//Explanation: Buyon day1(price =1)and sell on day 5(price = 5), profit = 5-1 = 4.
//Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
//engaging multiple transactions at the same time. You must sell before buying again.
//Example 3:
//Input:[7,6,4,3,1]Output:0
//Explanation:In this ase,no transaction is done, i.e. max profit = 0.

#include <stdio.h>
//贪心算法
int maxProfit(int* prices, int pricesSize) {
    int maxProfit = 0;

    for (int i = 1; i < pricesSize; ++i){
        // 只要今天的价格高于昨天的价格,就可以获利
        if (prices[i] > prices[i - 1]) {
            maxProfit += prices[i] - prices[i - 1];
        }
    }

    return maxProfit;
}

int main() {
    // 示例输入
    int prices1[] = {7, 1, 5, 3, 6, 4};
    int prices2[] = {1, 2, 3, 4, 5};
    int prices3[] = {7, 6, 4, 3, 1};

    printf("Example 1: Max Profit = %d\n", maxProfit(prices1, 6)); // 输出: 7
    printf("Example 2: Max Profit = %d\n", maxProfit(prices2, 5)); // 输出: 4
    printf("Example 3: Max Profit = %d\n", maxProfit(prices3, 5)); // 输出: 0

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

7yewh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值