首页 > 其他分享 >【LeeCode】122.买卖股票的最佳时机II

【LeeCode】122.买卖股票的最佳时机II

时间:2023-01-14 23:36:51浏览次数:51  
标签:int sum LeeCode maxProfit II Solution 122 prices new

【题目描述】

给你一个整数数组 ​​prices​​​ ,其中 ​​prices[i]​​​ 表示某支股票第 ​​i​​ 天的价格。

在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。

返回 你能获得的 最大 利润 。

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

【示例】

【LeeCode】122.买卖股票的最佳时机II_i++

【代码】​​代码随想录​

import java.util.*;
// 2023-1-14

class Solution {
public int maxProfit(int[] prices) {
int sum = 0;

for (int i = 1; i < prices.length; i++) {
if (prices[i] - prices[i - 1] > 0){
sum += prices[i] - prices[i - 1];
}
}
System.out.println(sum);
return sum;
}
}

public class Main {
public static void main(String[] args) {
new Solution().maxProfit(new int[]{7,1,5,3,6,4}); // 输出: 7
new Solution().maxProfit(new int[]{1,2,3,4,5}); // 输出: 4
new Solution().maxProfit(new int[]{7,6,4,3,1}); // 输出: 0
}
}


标签:int,sum,LeeCode,maxProfit,II,Solution,122,prices,new
From: https://blog.51cto.com/u_13682316/6007958

相关文章