买卖股票的最佳时机 II

例题:

https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/description/

分析:

某一天买入股票,未来任意一天卖出,只能卖了再买,但可以买卖多次,并允许同一天卖出后再买入,求最大利润。

因为要保证利润最大,只能逢涨就买入,遇跌不买。

有利润就买卖,只看眼前。

先定义两个指针i ,j ,i表示当前股票的价格, j表示下一天股票价格,只要有利润就记录。

代码实现:
java 复制代码
package leetcodeup;

public class ShareslLeetcode122 {

    public static int maxProfit(int[] prices) {
        int i = 0;
        int j = 1;
        int sum = 0;
        while(j < prices.length){
            if(prices[j] - prices[i] > 0){ //有利润
                sum += prices[j] - prices[i];
            }
            i++;
            j++;
        }
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(maxProfit(new int[]{9, 3, 12, 1, 2, 3})); // 11
        System.out.println(maxProfit(new int[]{7, 1, 5, 3, 6, 4})); // 7
    }
}
相关推荐
闲猫6 分钟前
LangChain / Core components / Models
开发语言·python·langchain
想做小南娘,发现自己是女生喵23 分钟前
第 2 章 顺序表和 vector
java·数据结构·算法
艾醒1 小时前
2026年第29周(7.13-7.19)AI全复盘:技术突破、行业趣闻翻车、算力服务器商业动态
人工智能·算法
CHANG_THE_WORLD1 小时前
6.多线程的TCP通信
java·网络·tcp/ip
雪碧聊技术2 小时前
动态规划算法—01背包问题
算法·动态规划
-银雾鸢尾-2 小时前
C#中的索引器
开发语言·c#
bu_shuo2 小时前
c与cpp中的argc和argv
c语言·c++·算法
普贤莲花2 小时前
【2026年第29周---写于20260718】---整理,断舍离
程序人生·算法·生活
Qlittleboy2 小时前
PHP的接口参数传递的过多,max_input_vars = 5000
开发语言·php
Reart2 小时前
Leetcode 674.最长连续递增序列 (719)
后端·算法