买卖股票的最佳时机 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
    }
}
相关推荐
江畔柳前堤5 小时前
roLabelImg 详细安装教程
开发语言·人工智能·后端·云原生
Wang's Blog5 小时前
Go-Zero 项目开发47:自研微服务框架的必要性与核心结构设计
开发语言·微服务·golang
白鸽(二般)6 小时前
MinIO Java Client API
java·开发语言
hPw0eKIqD6 小时前
C++ 模板参数推导问题小记(非推导上下文)
开发语言·c++
临床数据科学和人工智能兴趣组6 小时前
要使用 R Markdown,首先需要安装 R 和 RStudio,接着安装 rmarkdown 包
开发语言·数据挖掘·数据分析·r语言·r语言-4.2.1
普通攻击往后拉6 小时前
Leetcode 206. 反转链表
算法·leetcode·链表
软萌萌的17 小时前
Java Spring Boot 修改yml配置&加载顺序规则
java·spring boot·python
Nebula嵌入式7 小时前
【C语言】09-深入解析main函数
linux·c语言·开发语言·嵌入式
@syh.7 小时前
【贪心】矩阵消除游戏
算法·游戏·矩阵
IT小盘7 小时前
13-企业Prompt模板-角色任务约束与输出格式
java·前端·prompt