牛客网:NC134 买卖股票的最好时机(二)

package com.company.test.买卖股票的最好时机2;

/**
 * @author xienl
 * @description 买卖股票的最好时机
 * @date 2022/9/1
 */

public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();

    }

    /**
     * 动态规划
     * @param prices
     * @return
     */
    public int maxProfit (int[] prices) {
        // write code here
        int[][] dp = new int[prices.length][2];
        // 0 代表不持有股票, 1代表持有股票
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        for (int  i = 1; i < prices.length; i++){
            // 当天未持有股票。那么最大收益要么是之前未持有股票的收益。要么就是当天卖出股票的收益
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
            // 当天持有股票,结果是钱几天持有的最大值,或者说今天把股票卖出的最大值
            dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
        }
        // 最后一天不持股票的最大价值
        return dp[prices.length - 1][0];
    }

    /**
     * 贪心, 只需要计算当天是否是比前一天便宜,如果便宜就直接卖出
     * @param prices
     * @return
     */
    public int maxProfit2 (int[] prices) {
        // write code here
       int res = 0;
       for (int i = 1; i < prices.length; i++){
           if (prices[i] > prices[ i - 1]){
               res += prices[i] - prices[i - 1];
           }
       }
       return  res;
    }
}

### 牛客网 NC288209 题解 对于牛客网上编号为 NC288209 的题目,虽然具体题目细节未在此提供,但从常见算法题型出发可以推测这可能涉及特定的数据结构操作或是算法设计。为了给出更贴合实际需求的回答,假设此题与链表操作有关,特别是基于反转单链表这一经典问题[^5]。 #### 反转单链表的实现方法 针对此类问题的一种典型解决方案如下所示: ```cpp #include <iostream> using namespace std; // 定义链表节点结构体 struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* ReverseList(ListNode* pHead) { ListNode *pre = NULL, *cur = pHead, *tmpNext; while (cur != NULL){ tmpNext = cur->next; // 记录当前节点的下一个位置 cur->next = pre; // 将当前节点指向前一个节点 pre = cur; // 前进到下一组节点 cur = tmpNext; } return pre; // 返回新的头部节点 } ``` 上述代码实现了单链表的就地逆序转换功能,通过迭代方式逐个改变各节点指向来完成整个列表方向上的翻转过程。 #### Python 实现版本 考虑到不同编程语言的应用场景差异以及灵活性考虑,这里同样提供了Python版的实现方案: ```python class ListNode: def __init__(self, x): self.val = x self.next = None def reverse_list(p_head): prev = None current = p_head while current is not None: temp_next = current.next # 存储后续节点 current.next = prev # 修改当前节点的前驱 prev = current # 移动prev至current处 current = temp_next # 继续遍历剩余部分 return prev # 新的头结点即原尾部元素 ``` 以上两种语言分别展示了如何高效而简洁地解决单向链表逆转的问题。值得注意的是,在处理这类数据结构时,理解其内部机制非常重要,这样才能写出既有效又能满足各种边界条件要求的程序逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值