买卖股票的最佳时机 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
    }
}
相关推荐
handler012 分钟前
基础算法:分治
c语言·开发语言·c++·笔记·学习·算法·深度优先
Yzzz-F6 分钟前
Problem - D2 - Codeforces [插入计数]
算法
图图的点云库6 分钟前
点云深度学习算法概述
人工智能·深度学习·算法
2501_9249526913 分钟前
设计模式在C++中的实现
开发语言·c++·算法
菜鸟小九15 分钟前
hot100(71-80)
java·数据结构·算法
大傻^15 分钟前
LangChain4j 1.4.0 快速入门:JDK 11+ 基线迁移与首个 AI Service 构建
java·开发语言·人工智能
代码探秘者16 分钟前
【大模型应用】4.分块之六大策略
java·数据结构·后端·python·spring
码喽7号16 分钟前
Springboot学习六:MybatisPlus的多表查询以及分页查询
java·spring boot·学习
不想看见40417 分钟前
Implement Queue using Stacks栈和队列--力扣101算法题解笔记
笔记·算法·leetcode
DeepModel20 分钟前
【统计检验】T检验
算法