买卖股票的最佳时机 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
    }
}
相关推荐
invicinble1 天前
对于java基础
java·开发语言
knight_9___1 天前
RAG面试篇9
java·人工智能·python·算法·agent·rag
贾斯汀玛尔斯1 天前
每天学一个算法--Top-K 查询(Top-K Retrieval)
算法
石榴树下的七彩鱼1 天前
智能抠图API怎么选?AI抠图多语言接入实战(Python/Java/PHP/JS完整教程)
java·python·智能抠图·ai抠图·api接入·图片去背景·电商工具
逻辑驱动的ken1 天前
Java高频面试考点场景题13
java·开发语言·jvm·面试·求职招聘·春招
Evand J1 天前
【MATLAB代码介绍】无迹粒子滤波(Unscented Particle Filter),运动目标滤波定位
开发语言·matlab·粒子滤波·upf·无迹
bubiyoushang8881 天前
MATLAB考虑源荷不确定性的电力系统优化
开发语言·matlab
lclcooky1 天前
Spring Boot 整合 Keycloak
java·spring boot·后端
菜鸟丁小真1 天前
LeetCode hot100 -131.分割回文串
数据结构·算法·leetcode·知识点总结
贾斯汀玛尔斯1 天前
每天学一个算法--PageRank
算法