买卖股票的最佳时机 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
    }
}
相关推荐
十八朵郁金香18 分钟前
通俗易懂的DOM1级标准介绍
开发语言·前端·javascript
阿尔法波21 分钟前
python与pycharm如何设置文件夹为源代码根目录
开发语言·python·pycharm
菜鸟蹦迪24 分钟前
八股文实战之JUC:ArrayList不安全性
java
2501_9032386524 分钟前
Spring MVC配置与自定义的深度解析
java·spring·mvc·个人开发
xing251630 分钟前
pytest下allure
开发语言·python·pytest
眸笑丶34 分钟前
使用 Python 调用 Ollama API 并调用 deepseek-r1:8b 模型
开发语言·python
逻各斯35 分钟前
redis中的Lua脚本,redis的事务机制
java·redis·lua
计算机毕设指导637 分钟前
基于Springboot学生宿舍水电信息管理系统【附源码】
java·spring boot·后端·mysql·spring·tomcat·maven
计算机-秋大田44 分钟前
基于Spring Boot的兴顺物流管理系统设计与实现(LW+源码+讲解)
java·vue.js·spring boot·后端·spring·课程设计
enyp801 小时前
Qt QStackedWidget 总结
开发语言·qt