_122买卖股票的最佳时机II_贪心

2024-06-19 07:20

本文主要是介绍_122买卖股票的最佳时机II_贪心,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

_122买卖股票的最佳时机II_贪心

  • 原题链接:
  • 完成情况:
  • 解题思路:
      • Problem Description
      • Code Explanation
      • Summary
  • 参考代码:
    • _122买卖股票的最佳时机II_贪心
  • 错误经验吸取

原题链接:

_122买卖股票的最佳时机II_贪心

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

完成情况:

在这里插入图片描述

解题思路:

Sure! The given Java code solves the “Best Time to Buy and Sell Stock II” problem using a greedy algorithm. Let’s go through the code step-by-step:

Problem Description

The problem requires you to find the maximum profit from buying and selling a stock given its prices over several days. You can buy and sell multiple times, but you can only hold one share of the stock at a time.

Code Explanation

  1. Method Signature:

    public int maxProfit(int[] prices) {
    

    This is the method maxProfit which takes an array of integers prices as input and returns an integer representing the maximum profit.

  2. Initialization:

    int result = 0;
    

    Here, result is initialized to store the cumulative profit.

  3. Greedy Algorithm:

    for (int i = 1; i < prices.length; i++) {result += Math.max(0, prices[i] - prices[i-1]);
    }
    

    This loop iterates over the prices array starting from the second day (index 1) to the last day. For each day i, it calculates the profit made by buying the stock on day i-1 and selling it on day i:

    • prices[i] - prices[i-1] represents the profit if the stock is bought on day i-1 and sold on day i.
    • Math.max(0, prices[i] - prices[i-1]) ensures that only positive profits are added to result. If the difference is negative (meaning selling at a loss), it adds 0 instead.

    The greedy approach works because the problem allows for multiple transactions, even on the same day. By always taking advantage of every increase in stock price, we can ensure that the total profit is maximized.

  4. Return Result:

    return result;
    

    Finally, the method returns the accumulated profit stored in result.

Summary

The greedy algorithm used here is straightforward and efficient. It iterates through the price array once (O(n) time complexity), adding up all the positive differences between consecutive days. This ensures that every possible profit opportunity is taken, leading to the maximum profit by the end of the period. This approach is optimal for this problem because it takes advantage of every price increase without worrying about the specifics of when to buy and sell.

参考代码:

_122买卖股票的最佳时机II_贪心

package leetcode板块;public class _122买卖股票的最佳时机II_贪心 {/**** @param prices* @return*/public int maxProfit(int[] prices) {// 这道题由于说了可以同一天卖出买入,因此只需要考虑是否能够赚到钱,即可以int result = 0;for (int i = 1;i<prices.length;i++){result += Math.max(0,prices[i] - prices[i-1]);}return result;}
}

错误经验吸取

这篇关于_122买卖股票的最佳时机II_贪心的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1074365

相关文章

usaco 1.3 Barn Repair(贪心)

思路:用上M块木板时有 M-1 个间隙。目标是让总间隙最大。将相邻两个有牛的牛棚之间间隔的牛棚数排序,选取最大的M-1个作为间隙,其余地方用木板盖住。 做法: 1.若,板(M) 的数目大于或等于 牛棚中有牛的数目(C),则 目测 给每个牛牛发一个板就为最小的需求~ 2.否则,先对 牛牛们的门牌号排序,然后 用一个数组 blank[ ] 记录两门牌号之间的距离,然后 用数组 an

poj 3190 优先队列+贪心

题意: 有n头牛,分别给他们挤奶的时间。 然后每头牛挤奶的时候都要在一个stall里面,并且每个stall每次只能占用一头牛。 问最少需要多少个stall,并输出每头牛所在的stall。 e.g 样例: INPUT: 51 102 43 65 84 7 OUTPUT: 412324 HINT: Explanation of the s

poj 2976 分数规划二分贪心(部分对总体的贡献度) poj 3111

poj 2976: 题意: 在n场考试中,每场考试共有b题,答对的题目有a题。 允许去掉k场考试,求能达到的最高正确率是多少。 解析: 假设已知准确率为x,则每场考试对于准确率的贡献值为: a - b * x,将贡献值大的排序排在前面舍弃掉后k个。 然后二分x就行了。 代码: #include <iostream>#include <cstdio>#incl

AI基础 L9 Local Search II 局部搜索

Local Beam search 对于当前的所有k个状态,生成它们的所有可能后继状态。 检查生成的后继状态中是否有任何状态是解决方案。 如果所有后继状态都不是解决方案,则从所有后继状态中选择k个最佳状态。 当达到预设的迭代次数或满足某个终止条件时,算法停止。 — Choose k successors randomly, biased towards good ones — Close

从0到1,AI我来了- (7)AI应用-ComfyUI-II(进阶)

上篇comfyUI 入门 ,了解了TA是个啥,这篇,我们通过ComfyUI 及其相关Lora 模型,生成一些更惊艳的图片。这篇主要了解这些内容:         1、哪里获取模型?         2、实践如何画一个美女?         3、附录:               1)相关SD(稳定扩散模型的组成部分)               2)模型放置目录(重要)

POJ2010 贪心优先队列

c头牛,需要选n头(奇数);学校总共有f的资金, 每头牛分数score和学费cost,问合法招生方案中,中间分数(即排名第(n+1)/2)最高的是多少。 n头牛按照先score后cost从小到大排序; 枚举中间score的牛,  预处理左边与右边的最小花费和。 预处理直接优先队列贪心 public class Main {public static voi

ural 1820. Ural Steaks 贪心

1820. Ural Steaks Time limit: 0.5 second Memory limit: 64 MB After the personal contest, happy but hungry programmers dropped into the restaurant “Ural Steaks” and ordered  n specialty steaks

ural 1014. Product of Digits贪心

1014. Product of Digits Time limit: 1.0 second Memory limit: 64 MB Your task is to find the minimal positive integer number  Q so that the product of digits of  Q is exactly equal to  N. Inpu

每日一题|牛客竞赛|四舍五入|字符串+贪心+模拟

每日一题|四舍五入 四舍五入 心有猛虎,细嗅蔷薇。你好朋友,这里是锅巴的C\C++学习笔记,常言道,不积跬步无以至千里,希望有朝一日我们积累的滴水可以击穿顽石。 四舍五入 题目: 牛牛发明了一种新的四舍五入应用于整数,对个位四舍五入,规则如下 12345->12350 12399->12400 输入描述: 输入一个整数n(0<=n<=109 ) 输出描述: 输出一个整数

学习记录:js算法(二十八):删除排序链表中的重复元素、删除排序链表中的重复元素II

文章目录 删除排序链表中的重复元素我的思路解法一:循环解法二:递归 网上思路 删除排序链表中的重复元素 II我的思路网上思路 总结 删除排序链表中的重复元素 给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。 图一 图二 示例 1:(图一)输入:head = [1,1,2]输出:[1,2]示例 2:(图